在 C# 中执行 ExecuteNonQuery() 函数时出错
我正在使用从 gui 中的 TextBox 控件中提取的值从 c# 执行 Insert 语句。
我的数据库中只有 2 列不为空约束
,例如:我的插入语句都是 VARCHAR 字段,包括 ssn 和 dbate 是日期类型
insert into emp (fname,minit,lname,dbate,ssn,sex) values ('arun','','','','12345','')
如果输入了所有值,但当我输入时,这可以正常工作null 值,我在执行语句时遇到像上面的语句一样的 Data MisMatch 错误。直接在 sql2005 中执行 sql 时,查询工作正常。
string myInsertQuery = "INSERT INTO Employee (fname,minit,lname,ssn,bdate,address,sex) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "')";
OleDbCommand myCommand2 = new OleDbCommand(myInsertQuery, mycon)
myCommand2.ExecuteNonQuery();
I'm executing an Insert statement from c# with values extracted from TextBox Controls in my gui.
I've only 2 columns with not null constrain in my DB
for eg : my insert statement is all are VARCHAR
fields including ssn and dbate is date type
insert into emp (fname,minit,lname,dbate,ssn,sex) values ('arun','','','','12345','')
This works fine if all values are entered but when I enter null values, I get Data MisMatch error like a statement above while executing the statement .while executing sql directly in sql2005 the query works fine .
string myInsertQuery = "INSERT INTO Employee (fname,minit,lname,ssn,bdate,address,sex) values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + textBox6.Text + "','" + textBox7.Text + "')";
OleDbCommand myCommand2 = new OleDbCommand(myInsertQuery, mycon)
myCommand2.ExecuteNonQuery();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能想尝试:
检查用户是否键入了一些字符,例如 ' 和 - 它很容易破坏您的语法!
离题但相关:直接从您允许的文本框中获取值任何人都可以在您的应用程序上注入 SQL,因此这是一个缺陷。您可以通过参数化查询来避免这种情况,例如:
You might wanna try:
Check if the user is typing some characters like ' and -- it can easily corrupt your syntax!!!
OFF-TOPIC BUT RELATED: By getting your values directly from the textbox youre allowing anyone to inject SQL on your application, its therefore a flaw. You can avoid it by parametrizing your query, such as follow:
如果
dbdate
是date
类型,正如你所说,如果textbox5中的值,你得到一个
不包含适当格式的文本。例如“2011 年 10 月 12 日”类型不匹配错误
是正常的If
dbdate
isdate
type, as you say it is, it's normal that you get atype mismatch error
if the value intextbox5
does not contain text in an appropriate format. e.g. '10-12-2011'也许您应该考虑在某个地方对文本框进行验证,以确保它们包含适当的值。
(如果它们为空,请务必输入 string.empty 值或应用程序所需的任何默认值)。
很难判断,因为您的代码有点不完整,无法给出更准确的答案。
Maybe you should consider somewhere to make a verification of your textbox to make sure they contains an appropriate value.
(If they are empty, be sure to put a string.empty value or any default value required by your application).
Difficult to tell otherwise because your code is a litle bit incomplete to give a more precise answer.