SQL插入查询使用C# [英] SQL Insert Query Using C#

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

问题描述

我有在此我试图解决当下的问题。我只是试图访问一个数据库,并插入一些值与C#

I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#

我尝试的事情(工作)

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc',      'abc', 'abc', 'abc')";

一个新行插入,一切工作正常,现在我试图插入使用变量行:

A new line was inserted and everything worked fine, now I tried to insert a row using variables:

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id, @username, @password, @email)";

command.Parameters.AddWithValue("@id","abc")
command.Parameters.AddWithValue("@username","abc")
command.Parameters.AddWithValue("@password","abc")
command.Parameters.AddWithValue("@email","abc")

command.ExecuteNonQuery();

没有工作,插入任何值。我想一件事

Didn't work, no values were inserted. I tried one more thing

command.Parameters.AddWithValue("@id", SqlDbType.NChar);
command.Parameters["@id"].Value = "abc";

command.Parameters.AddWithValue("@username", SqlDbType.NChar);
command.Parameters["@username"].Value = "abc";

command.Parameters.AddWithValue("@password", SqlDbType.NChar);
command.Parameters["@password"].Value = "abc";

command.Parameters.AddWithValue("@email", SqlDbType.NChar);
command.Parameters["@email"].Value = "abc";

command.ExecuteNonQuery();

五月谁能告诉我什么,我做错了什么?

May anyone tell me what I am doing wrong?

亲切的问候

编辑:

在一个其他线路我创建一个新的SQL命令

in one other line I was creating a new SQL-Command

var cmd = new SqlCommand(query, connection);

仍然没有工作,我不能发现任何错误在code以上。

Still not working and I can't find anything wrong in the code above.

推荐答案

我假设你有你的数据库的连接,并使用C#你不能做插入的参数。

I assume you have a connection to your database and you can not do the insert parameters using c #.

您不能在查询添加参数。它应该看起来像:

You are not adding the parameters in your query. It should look like:

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES(@id,@username,@password, @email)";

SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");

command.ExecuteNonQuery();

这篇关于SQL插入查询使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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