在C#中的SQL插入查询不更新数据库 [英] SQL insert query in C# does not update database
问题描述
这是我下面的代码。该程序运行良好。我没有得到任何异常。但在最后,该表不包含新插入的行。 (注意,连接字符串是正确的)
字符串名称=MYNAME;
串年龄=myage;
字符串SQL =INSERT INTO学生(姓名,年龄)VALUES('+姓名+,+年龄+');
SqlConnection的康恩=新的SqlConnection(ConfigHelper.GetConnectionString());
的SqlCommand CMD =新的SqlCommand(SQL,conn);在
cmd.ExecuteNonQuery();
conn.Close();
首先:开始使用参数化查询!,否则你的代码始终是敞开的SQL注入攻击 - 而不是你想有对付的东西。
假设你正在使用此功能(取决于在连接字符串,你有没有在原来的问题向我们展示):整个的用户实例和AttachDbFileName = 的方法是有缺陷的 - 在最好的! Visual Studio将被复制周围的密度纤维板
文件和最有可能的,您插入
作品就好了 - 但你只是在看错密度纤维板最终文件!
如果你想坚持使用这种方法,然后尝试把一个断点上的 myConnection.Close()
通话 - 然后检查与SQL Server管理Studio快速的密度纤维板
文件 - 我几乎可以肯定你的数据是否有
在真正的解决方案在我看来,将
-
安装SQL Server Express(和你已经做到这一点无论如何)
-
安装SQL Server Management Studio中快速
-
在 SSMS快递,给它一个合理的名称(如
VictoryDatabase
) -
连接使用其逻辑的数据库名称为(当你在服务器上创建它交给) - 和周围不乱用物理数据库文件和用户实例。在这种情况下,您的连接字符串会是这样:
数据源= .\\SQLEXPRESS;数据库= VictoryDatabase;集成安全性= TRUE
和其他一切都是究竟和以前一样。 ..
This is my code below. The program runs fine. I don't get any exceptions. But in the end, the table doesn't contain the newly inserted row. (Note, the connection string is correct).
string Name = "myname";
string Age = "myage";
string sql = "INSERT INTO Student (Name, Age) VALUES ('" + Name + "','" + Age + "')";
SqlConnection conn = new SqlConnection(ConfigHelper.GetConnectionString());
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
First of all: start using parametrized queries! Otherwise your code is always open to SQL injection attacks - not something you want to have to deal with.
Assuming you are using this feature (depends on the connection string, which you haven't shown us in the original question): the whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf
file and most likely, your INSERT
works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close()
call - and then inspect the .mdf
file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g.
VictoryDatabase
)connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=VictoryDatabase;Integrated Security=True
and everything else is exactly the same as before...
这篇关于在C#中的SQL插入查询不更新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!