主题:ADO.Net中SqlConnection、SqlCommand的应用
1、SqlConnection
(1)使用SqlConnection类可以连接到SQL Server数据库。SqlConnection对象的主要属性和方法如下:
——属性:ConnectionString(连接字符串)
——方法:Open(打开数据库连接)
Close(关闭数据库连接)
(2)连接数据库主要分以下三步:
——定义字符串
——创建SqlConnection对象,代码如下:
SqlConnection sqlConnection = new SqlConnection();
——打开数据库连接,代码如下:
sqlConnection.Open();
2、SqlCommand
(1)SqlCommand对象用于执行具体的SQL语句,如增加、删除、修改、查找。SqlCommand对象的使用步骤如下。
——创建SqlConnection对象。
——定义SQL语句。
——创建SqlCommand对象。
——调用SqlCommand对象的某个方法,执行SQL语句。
思维导图:
代码:
private void btn_SignUp_Click(object sender, EventArgs e)
{
if (this.txb_UserNo.Text.Trim() == “”)
{
MessageBox.Show(“用户号不能为空!”);
this.txb_UserNo.Focus();
return;
}
if (this.txb_Password.Text.Trim() == “”)
{
MessageBox.Show(“密码不能为空!”);
this.txb_Password.Focus();
return;
}
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
“Server=(local);Database=EduBaseDemo;Integrated Security=sspi”;
SqlCommand sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandText =
“INSERT tb_User (No,Password) VALUES(@No,HASHBYTES(‘MD5’,@Password));”;
sqlCommand.Parameters.AddWithValue("@No", this.txb_UserNo.Text.Trim());
sqlCommand.Parameters.AddWithValue("@Password", this.txb_Password.Text.Trim());
sqlCommand.Parameters["@Password"].SqlDbType = SqlDbType.VarChar;
int rowAffected = 0;
string message = “”;
try
{
sqlConnection.Open();
rowAffected = sqlCommand.ExecuteNonQuery();
}
catch (SqlException sqlEx)
{
if (sqlEx.Number == 2627)
{
message = “您注册的用户号已存在,请重新输入!”; //给出合适的错误提示;
}
else
{
message = “注册失败!”;
}
}
finally
{
sqlConnection.Close();
}
if (rowAffected == 1)
{
message = “注册成功。”;
}
MessageBox.Show(message);
}