gpt4 book ai didi

c# - 向我的数据库程序插入函数的问题

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:30 25 4
gpt4 key购买 nike

大家好!我的程序插入有一个小问题。看,代码没有错误,但我在尝试插入时遇到 OleDb 异常。我项目的其他部分工作正常,但这里有一个我似乎找不到的小问题

 public void Insert()
{
//myDb = new OleDbConnection(conn + dbFile);
myDb.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Employee", myDb);
//
OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, Password, email, phone) VALUES ('" + insUn + "','" + insPass + "','" + insNm + "','" + insNmr + "')", myDb);

adapter.InsertCommand = cmd;

adapter.InsertCommand.ExecuteNonQuery();



DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");

dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Employee";

myDb.Close();
}

其他功能如搜索和删除都可以,但我在这里找不到问题

这些是异常(exception)情况:

 try
{
if (textBox2.Text != "")
{
insUn = textBox2.Text;
insNmr = textBox4.Text;
insPass = textBox3.Text;
insNm = textBox5.Text;
}
Insert();
}
catch (OleDbException ex)
{
MessageBox.Show("Error, please try again", "Exception", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
}
catch (FormatException ex)
{
MessageBox.Show("One or more fields have not been entered. Please check and re-enter", "Missing fields", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}



enter code here

最佳答案

Abdellah 的回答会奏效,但在构建查询字符串时要注意 SQL 注入(inject)攻击。你应该像这样构建它:

OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, Password, email, phone) VALUES (@p1, @p2, @p3, @p4)", myDb);
int maxSize = 50;
cmd.Paramters.Add("@p1", SqlDbType.VarChar, maxSize).Value = insUn;
cmd.Parameters.Add("@p2", SqlDbType.VarChar, maxSize).Value = insPass;
cmd.Parameters.Add("@p3", SqlDbType.VarChar, maxSize).Value = insNm;
cmd.Parameters.Add("@p4", SqlDbType.VarChar, maxSize).Value = insNmr;

关于c# - 向我的数据库程序插入函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37190197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com