SQL数据库插入问题 [英] Sql database insert problem

查看:90
本文介绍了SQL数据库插入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据插入数据库.

这是我的代码:

Hi, I''m trying to insert data into a database.

This is my code:

SqlCeConnection conn = new SqlCeConnection(connStr);
conn.Open();

string cmd = "INSERT INTO Log(Type,Rego) VALUES(" + typeBox.Text + "," +     regoBox.Text + ")";

SqlCeCommand writeToDB = new SqlCeCommand(cmd, conn);
writeToDB.ExecuteNonQuery();
conn.Close();



Type是一个ntext列,Rego是一个浮点数.当我将DA40放入typeBox中并将3.0放入regoBox中时,出现此错误:

列名无效. [节点名称(如果有)=,列名称= DA40]

我在做傻事吗?
感谢您提供一些帮助,谢谢



Type is an ntext column and Rego is a float. When I put DA40 in typeBox and 3.0 in regoBox I come up with this error:

The column name is not valid. [Node name (if any)=,Column name=DA40]

Am I doing something silly?
Some help would be most appreciated, thanks

推荐答案

问题是您需要在Type值的两边加上单引号.由于SQL注入和其他问题,在使用SQL时不赞成使用字符串连接.您应该养成使用参数化查询的习惯.

The problem is that you need to have single quotes around the value for Type. Using string concatenation is frowned upon when working with SQL because of SQL injection and other issues. You should get in the habit of using parameterized queries.

string cmd = "INSERT INTO Log(Type, Rego) VALUES('" + typeBox.Text + "'," + regoBox.Text + ")";



参数化查询版本.



Parameterized Query Version.

SqlCeConnection conn = new SqlCeConnection(connStr);
conn.Open();
 
string cmd = "INSERT INTO Log(Type, Rego) VALUES(@Type, @Rego)";
 
SqlCeCommand writeToDB = new SqlCeCommand(cmd, conn);
writeToDB.Parameters.Add(new SqlCeParameter("@Type", typeBox.Text);
writeToDB.Parameters.Add(new SqlCeParameter("@Rego", regoBox.Text);
writeToDB.ExecuteNonQuery();
conn.Close();


您忘了用''(单引号)将类型列的值括起来.另外,请注意,这不是编写查询的好方法.在将值放入SqlCommand时使用参数.请参见此处 [
You forgot to enclose the value of the type column with ''(Single Quotes). Also, please note that this is not a good way to write queries. Use parameters in putting values to your SqlCommand. See here[^] for reference.


您做了一件大事.

you have done one mistak.

string cmd = "INSERT INTO Log(Type,Rego) VALUES('" + typeBox.Text + "'," + regoBox.Text + ")";



将此行放入您的代码中.



put this line into ur code.


这篇关于SQL数据库插入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆