[英]c# winform program connect to a sql database
I'm creating ac# winform and I need to connect with a sql database which I already have, basically I need to registered users to log into the program using username and password..but I'm having issues with the db connection I guess, there's a run time error "connection property has not been initialized!" 我正在创建ac#winform,需要连接一个已经存在的sql数据库,基本上我需要注册用户才能使用用户名和密码登录该程序。但是我猜数据库连接有问题,出现运行时错误“连接属性尚未初始化!”
I used this same connection string and my login form connected successfully.. 我使用了相同的连接字符串,并且登录表单成功连接。
String cs = (@"Data Source=DESKTOP-3BDK76K\SQLEXPRESS;Initial Catalog=FurnitureOrdering;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection myConnection = default(SqlConnection);
myConnection = new SqlConnection(cs);
SqlCommand myCommand = default(SqlCommand);
myCommand = new SqlCommand("SELECT username,password FROM Register WHERE username= @username AND password = @password");
SqlParameter uName = new SqlParameter("@username", SqlDbType.VarChar);
SqlParameter uPassword = new SqlParameter("@password", SqlDbType.VarChar);
uName.Value = txtUserName.Text;
uPassword.Value = txtPassword.Text;
myCommand.Parameters.Add(uName);
myCommand.Parameters.Add(uPassword);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (myReader.Read() == true)
{
MessageBox.Show("Successfully logged-in"+ txtUserName.Text);
this.Hide();
Main_UI ss2 = new Main_UI();
ss2.Show();
}
else
{
MessageBox.Show("Login failed!");
txtUserName.Clear();
txtPassword.Clear();
}
if (myConnection.State == ConnectionState.Open)
{
myConnection.Dispose();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
error message 错误信息
"connection property has not been initialized!" “连接属性尚未初始化!”
您必须设置SqlCommand对象的连接属性。
myCommand.Connection = myConnection;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.