我无法插入DataBase [英] I can not Insert into DataBase
问题描述
我想在我的数据库中插入字符串输入文本框,但是错误:
I want insert string entry textbox into my database, but error:
SqlConnection conn = new SqlConnection(@"Data Source=.;Initial Catalog=QLSV_LogIn;uid = sa; pwd = 123456");
private void btnCap_nhat_Click(object sender, EventArgs e)
{
try
{
if (txtKhoa.Text == "")
{
MessageBox.Show("Empty","Eror 1");
txtKhoa.Focus();
}
else
{
conn.Open();
SqlCommand cmd = new SqlCommand("Insert Into tblKhoa (TenKhoa) Value('" + txtKhoa.Text + "')", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Success");
conn.Close();
txtKhoa.Text = "";
txtKhoa.Focus();
}
}
catch
{
MessageBox.Show("Error 2");
}
}
当我插入时,它显示错误2 ???为什么???帮帮我
when i insert, it show Error 2??? Why??? Help me
推荐答案
更改:
Change:
catch
{
MessageBox.Show("Error 2");
}
要
To
catch (Exception ex)
{
MessageBox.Show(ex.tostring());
}
并告诉我们错误是什么!
And tell us what the error is!
将Value替换为此行中的Values ..
更改此
Replace "Value" to "Values" in this line..
Change this
SqlCommand cmd = new SqlCommand("Insert Into tblKhoa (TenKhoa) Value('" + txtKhoa.Text + "')", conn);
到
To
SqlCommand cmd = new SqlCommand("Insert Into tblKhoa (TenKhoa) Values('" + txtKhoa.Text + "')", conn);
正确的几点。
你需要参数化你的try,catch块:
Right a few pointers.
You need to parametrise your try, catch block:
try
{
//Do something
}
catch(Exception ex)
{
//ex contains the error information.
}
A. lso将文本值连接到命令中将打开SQL注入。
如果我输入:
GO从tblKhoa删除GO
在您的文本框中,我可以删除该行中的所有记录。
您应该使用参数。
Also concatenating the the text value into the command is going to open you up to SQL injection.
If I entered:
GO delete from tblKhoa GO
Into your text box it's possible I could delete all the records from the row.
You should use parameters.
SqlCommand cmd = new SqlCommand("Insert Into tblKhoa (TenKhoa) Value(@MyValue)", conn);
IDbDataParameter param = cmd.CreateParameter();
param.Name = "@MyValue";
param.Type = DbType.String;
param.Value = txtKhoa.Text;
cmd.Parameters.Add(param);
这会阻止用户在文本框中包含SQL语法并造成损坏到您的数据库。
This stop the user including SQL syntax in the text box and cause damage to your database.
这篇关于我无法插入DataBase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!