如何将注册的数据写入数据库
真正实现将注册的账户密码写入数据库(就是程序运行后再去数据库中能查看到数据),而不是写入内存中,具体的语句是什么?我是新手,求大家详细指点指点,非常感谢。
C# code
//连接字符串
ConnectionStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\360data\重要数据\我的文档\用户注册信息.mdf;
Integrated Security=True;Connect Timeout=30;User Instance=True";
//创建连接对象
SqlConnection sqlCon = new SqlConnection(ConnectionStr);
//建立插入命令字符串
insertStr = "INSERT INTO 注册信息保存 (username,password,e-mail) VALUES ('"
+ TextBox1.Text + "','" + TextBox2.Text
+ "','"+TextBox4.Text+"')";
try
{
//打开数据
sqlCon.Open();
if (sqlCon.State == ConnectionState.Open)
{
//创建命令对象
SqlCommand sqlComm = new SqlCommand(insertStr, sqlCon);
}
}
catch
{
if (sqlCon.State != ConnectionState.Open)
{
}
}
finally
{
//关闭数据库
sqlCon.Close();
}
在这代码中少了什么语句?求大家详细指点指点,非常感谢。
------解决方案--------------------insertStr = "INSERT INTO 注册信息保存 (username,password,e-mail) VALUES ('"
+ TextBox1.Text + "','" + TextBox2.Text
+ "','"+TextBox4.Text+"')";
最好写成 参数化查询
insertStr = "INSERT INTO 注册信息保存 ([username],[password],[e-mail]) VALUES (@username,@password,@email)";
try
{
//打开数据
if (sqlCon.State != ConnectionState.Open)
{
sqlCon.Open();
//创建命令对象
SqlCommand sqlComm = new SqlCommand(insertStr, sqlCon);
sqlComm.Parameters.AddWithValue("@username",TextBox1.Text );
sqlComm.Parameters.AddWithValue("@password",TextBox2.Text );
sqlComm.Parameters.AddWithValue("@email",TextBox4.Text );
sqlComm.ExecuteNonQuery();
}
}
catch
{
}
finally
{
//关闭数据库
sqlCon.Close();
}
------解决方案--------------------参数化查询是为了避免
SQL注入攻击
------解决方案--------------------C# code
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
------解决方案--------------------