[英]how do i check if my program is connected with my MSQL database in C#?
您好,我是一名学生,我被困在零件上,我需要检查问题是否与我的连接或我的代码有关,请不要告诉我我的代码有问题吗?我应该使用哪种方式检查MySql数据库是否已连接? 是的,我停用了其余代码以检查其代码。
private void Btnlogin_Click_1(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("Data Source=localhost; user id = root; Password =''; Database = login; SslMode=none");
Debug.WriteLine(con);
/* MySqlDataAdapter sda = new MySqlDataAdapter("Select Count(*) from users where id='" + Txtusername + "' and pword='" + Txtpassword + "' ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
main ss = new main();
ss.Show();
}
else
{
MessageBox.Show("failed to login please check your username and password");
}*/
尝试这种方式:
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
try
{
connection.Open();
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.CommandTimeout = 60 * 5;
using (MySqlDataReader dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
//Reading code..
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
关于此代码的注释:
1)拥有IDisposable
对象时,请始终使用using
语句
2) connection.Open();
指令,将尝试打开与数据库的连接。 如果它不起作用,它将抛出异常,该异常将被此代码中定义的try...catch
名称空间专案名称{公共部分类别登入:表格{SqlConnection cn = new SqlConnection(“此处为连接字串”);
public login()
{
InitializeComponent();
}
private void freshrationpurchase_Load(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cn.Open();
cmd.CommandText = "select count( *) from user where id=@";
SqlDataReader dr;
dr=cmd.ExecuteReader();
cn.Close();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.