如何连接数据库

问题描述:

SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=Test;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("select role from login where username='" + textBox1.Text + "' and password='" + textBox2.Text + "' ",con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count==1)
{
    this.Hide();
    MDIParent1 kk = new MDIParent1();
    kk.Show();

你错过了开场部分...

创建新的连接对象后,您应该打开连接,如下所示:

You are missing the opening part...
After creating a new connection object you should open the connection, like this:
con.Open





https:/ /msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx [ ^ ]


首先是创建SqlConnection对象但不是打开连接。



其次总是使用参数化查询来避免SQL注入。以下是完整的代码:

Firstly it is creating SqlConnection object but not open connection.

Secondly always use parameterized query to avoid SQL Injection. Here is the complete code:
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=Test;Integrated Security=True");
con.Open();

SqlDataAdapter sda = new SqlDataAdapter("select role from login where username = @uid and password = @pwd",con);
da.SelectCommand.Parameters.AddWithValue("@uid", textBox1.Text);
da.SelectCommand.Parameters.AddWithValue("@pwd", textBox2.Text);

DataTable dt = new DataTable();
sda.Fill(dt);

if (dt.Rows.Count==1)
{
  // Your logic
}

con.Close();


SqlConnection con=new SqlConnection("Data Source=USER-PC;Initial Catalog=Test;Integrated Security=True");
SqlCommand cmd=new SqlCommand();
SqlDataAdapter ada=new SqlDataAdapter();
DataTable dt=new DataTable();

cmd.Connection=con;
cmd.CommandText="select role from login where username='" + textBox1.Text + "' and password='" + textBox2.Text + "' ";
ada.SelectCommand=cmd;
ada.Fill(dt);

if(dt.Rows.Count>0)
{
this.Hide();
   MDIParent1 kk = new MDIParent1();
   kk.Show();

}













OR


SqlConnection con=new SqlConnection("Data Source=USER-PC;Initial Catalog=Test;Integrated Security=True");
SqlCommand cmd=new SqlCommand();
SqlDataAdapter ada=new SqlDataAdapter();
DataTable dt=new DataTable();
 
cmd.Connection=con;
cmd.CommandText="select role from login where username=@username and password=@password ";
cmd.Parameters.AddWithValue("@username",textBox1.Text.Trim());
cmd.Parameters.AddWithValue("@password",textBox2.Text.Trim());
ada.SelectCommand=cmd;
ada.Fill(dt);
 
if(dt.Rows.Count>0)
{
this.Hide();
   MDIParent1 kk = new MDIParent1();
   kk.Show();
 
}