将参数从C#对象传递给SQL

时间:2013-06-06 01:35:59

标签: c# sql-server visual-studio-2012

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace iss_farmacie_spitali
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            sqlConnection1.Open();
            sqlCommand1.Parameters.AddWithValue("user",textBox1.Text);
            sqlCommand1.Parameters.AddWithValue("pass",textBox2.Text);
            sqlCommand1.CommandText = "SELECT id,parola FROM ANGAJAT WHERE id=(user) AND    parola=(pass)";
            if (sqlCommand1.ExecuteNonQuery()!=null)
                MessageBox.Show("ESTE");
            sqlConnection1.Close();
        }
    }
}

我希望完成的是构建功能登录。我有一个数据库,一个名为“angajati”(员工)的表,其中包含id(实际上是用户名)和parola(密码)。我想知道的是我可以在SQL脚本文本中引入“变量”,让它像函数一样运行,只需从我的文本框中传递值。这是我用其他例子编写的,但它似乎不起作用。有人可以就此事给我一些见解吗?

1 个答案:

答案 0 :(得分:3)

private void button1_Click(object sender, EventArgs e)
        {
            sqlConnection1.Open();
            sqlCommand1.Parameters.AddWithValue("@user",textBox1.Text);
            sqlCommand1.Parameters.AddWithValue("@pass",textBox2.Text);
            sqlCommand1.CommandText = "SELECT id,parola FROM ANGAJAT WHERE id='@user' AND    parola='@pass'";
            if (sqlCommand1.ExecuteNonQuery()!=null)
                MessageBox.Show("ESTE");
            sqlConnection1.Close();
        }