如何连接数据库 [英] How do I connect to database
本文介绍了如何连接数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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();
}
这篇关于如何连接数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文