如何在Microsoft Visual Studio和C#中使用Sql将数据插入表中? [英] How Do I Insert Data Into A Table Using Sql In Microsoft Visual Studio And C#?

查看:146
本文介绍了如何在Microsoft Visual Studio和C#中使用Sql将数据插入表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试使用C#和SQL将数据添加到表中。我有以下代码,它似乎接受了代码,但是当我查看'show table data'时,该表尚未更新。我已使用列表框对此进行了测试,并使用新数据显示更新的表。使用SELECT语句填充列表框。

任何帮助将不胜感激。



Hi there, I am attempting to add data into a table using C# and SQL. I have got the following code and it seems to accept the code however when I look in the 'show table data' the table has not been updated. I have tested this by using a list box and the updated table is shown with the new data. The list box is populated by using a SELECT statement.
Any Help would be greatly appreciated.

string strCon = Properties.Settings.Default.TestingDatabaseConnectionString;
SqlConnection sqlConn = new SqlConnection(strCon);
SqlCommand cmd;
string cmdStr = "INSERT INTO tblContactsTest (Name, Number) VALUES('"+txtName.Text + "','" + txtNumber.Text + "')";
int ra = 0;
sqlConn.Open();
cmd = new SqlCommand(cmdStr, sqlConn);
ra = cmd.ExecuteNonQuery();
sqlConn.Close();

推荐答案

请不要这样做...不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。

Please don't do it like that...Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
string cmdStr = "INSERT INTO tblContactsTest (Name, Number) VALUES(@NM, @NO)";
int ra = 0;
sqlConn.Open();
using (cmd = new SqlCommand(cmdStr, sqlConn))
   {
   sqlConn.Parameters.AddWithValue("@NM", txtName.Text);
   sqlConn.Parameters.AddWithValue("@NO", txtNumber.Text);
   ra = cmd.ExecuteNonQuery();
   }

然后检查 ra 并确保它不为零。



如果是,那么SQL说它插入正常,所以你需要看看你是如何检查它是否保存。首先使用SSMS查看原始数据,然后查看SELECT以及何时执行。

Then check ra and make sure it is non-zero.

If it is, then SQL is saying it inserted ok, so you need to look at how you are checking to see if it saved or not. Start by using SSMS to look at the "raw" data, then look at your SELECT and when it is executed.


这篇关于如何在Microsoft Visual Studio和C#中使用Sql将数据插入表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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