C# 使用C语言的SQL插入查询#

C# 使用C语言的SQL插入查询#,c#,sql,sql-server-express,C#,Sql,Sql Server Express,我现在有一个问题,我正在努力解决。我只是试图在C语言的帮助下访问数据库并插入一些值# 我尝试过的事情(成功了) 插入了新行,一切正常,现在我尝试使用变量插入一行: String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id, @username, @password, @email)"; command.Parameters.AddWithValue("@id","abc") command.P

我现在有一个问题,我正在努力解决。我只是试图在C语言的帮助下访问数据库并插入一些值#

我尝试过的事情(成功了)

插入了新行,一切正常,现在我尝试使用变量插入一行:

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();
无效,未插入任何值。我又试了一件事

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();
谁能告诉我我做错了什么

问候

编辑:

public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
    SqlConnection connection = new SqlConnection(ConnectionString);
    try
    {
        using (SqlCommand cmd = new SqlCommand(query, connection))
        {   // for cases where no parameters needed
            if (parameters != null)
            {
                cmd.Parameters.AddRange(parameters.ToArray());
            }

            connection.Open();
            int result = cmd.ExecuteNonQuery();
            return result;
        }
    }
    catch (Exception ex)
    {
        AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
        return 0;
        throw;
    }

    finally
    {
        CloseConnection(ref connection);
    }
}

private static void CloseConnection(ref SqlConnection conn)
{
    if (conn.State != ConnectionState.Closed)
    {
        conn.Close();
        conn.Dispose();
    }
}
在另一行中,我创建了一个新的SQL命令

var cmd = new SqlCommand(query, connection);
仍然无法工作,我在上面的代码中找不到任何错误。

最常见的错误(尤其是在使用express时)“我的插入没有发生”是:查找错误的文件

如果您使用的是基于文件的express(而不是强附件),则项目文件夹中的文件(例如,
c:\dev\myproject\mydb.mbd
)不是程序中使用的文件。构建时,会将该文件复制到
c:\dev\myproject\bin\debug\mydb.mbd
;您的程序在
c:\dev\myproject\bin\debug\
的上下文中执行,因此您需要查看此处的是否确实发生了编辑。要确认:在应用程序中查询数据(插入后)。

尝试

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username, @password, @email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
    //a shorter syntax to adding parameters
    command.Parameters.Add("@id", SqlDbType.NChar).Value = "abc";

    command.Parameters.Add("@username", SqlDbType.NChar).Value = "abc";

    //a longer syntax for adding parameters
    command.Parameters.Add("@password", SqlDbType.NChar).Value = "abc";

    command.Parameters.Add("@email", SqlDbType.NChar).Value = "abc";

    //make sure you open and close(after executing) the connection
    connection.Open();
    command.ExecuteNonQuery();
}

我假设您已连接到数据库,并且无法使用c#插入参数

您没有在查询中添加参数。它应该是这样的:

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();
更新:

using(SqlConnection connection = new SqlConnection(_connectionString))
{
    String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

    using(SqlCommand command = new SqlCommand(query, connection))
    {
        command.Parameters.AddWithValue("@id", "abc");
        command.Parameters.AddWithValue("@username", "abc");
        command.Parameters.AddWithValue("@password", "abc");
        command.Parameters.AddWithValue("@email", "abc");

        connection.Open();
        int result = command.ExecuteNonQuery();

        // Check Error
        if(result < 0)
            Console.WriteLine("Error inserting data into Database!");
    }
}
使用(SqlConnection连接=新的SqlConnection(_connectionString))
{
String query=“插入dbo.SMS_PW(id、用户名、密码、电子邮件)值(@id、@username、@password、@email)”;
使用(SqlCommand=newsqlcommand(查询、连接))
{
command.Parameters.AddWithValue(“@id”,“abc”);
command.Parameters.AddWithValue(“@username”,“abc”);
command.Parameters.AddWithValue(“@password”,“abc”);
command.Parameters.AddWithValue(“@email”,“abc”);
connection.Open();
int result=command.ExecuteNonQuery();
//检查错误
如果(结果<0)
WriteLine(“将数据插入数据库时出错!”);
}
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
String query=“插入到产品(productid、productname、productdesc、productqty)值(@txtitemid、@txtitemname、@txtitemdesc、@txtitemqty)”;
尝试
{
使用(SqlCommand=newsqlcommand(query,con))
{
command.Parameters.AddWithValue(“@txtitemid”,txtitemid.Text);
command.Parameters.AddWithValue(“@txtitemname”,txtitemname.Text);
command.Parameters.AddWithValue(“@txtitemdesc”,txtitemdesc.Text);
command.Parameters.AddWithValue(“@txtitemqty”,txtitemqty.Text);
con.Open();
int result=command.ExecuteNonQuery();
//检查错误
如果(结果<0)
MessageBox.Show(“错误”);
MessageBox.Show(“记录…!”,“消息”,MessageBoxButtons.OK,MessageBoxIcon.Information);
con.Close();
加载器();
}
}
捕获(例外情况除外)
{
MessageBox.Show(例如Message);
con.Close();
}
}

我刚刚为此编写了一个可重用方法,这里没有关于可重用方法的答案,所以为什么不共享…
这是我当前项目的代码:

public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
    SqlConnection connection = new SqlConnection(ConnectionString);
    try
    {
        using (SqlCommand cmd = new SqlCommand(query, connection))
        {   // for cases where no parameters needed
            if (parameters != null)
            {
                cmd.Parameters.AddRange(parameters.ToArray());
            }

            connection.Open();
            int result = cmd.ExecuteNonQuery();
            return result;
        }
    }
    catch (Exception ex)
    {
        AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
        return 0;
        throw;
    }

    finally
    {
        CloseConnection(ref connection);
    }
}

private static void CloseConnection(ref SqlConnection conn)
{
    if (conn.State != ConnectionState.Closed)
    {
        conn.Close();
        conn.Dispose();
    }
}
公共静态int参数命令(字符串查询,列表参数)
{
SqlConnection连接=新的SqlConnection(ConnectionString);
尝试
{
使用(SqlCommand cmd=newsqlcommand(查询、连接))
{//适用于不需要参数的情况
if(参数!=null)
{
cmd.Parameters.AddRange(Parameters.ToArray());
}
connection.Open();
int result=cmd.ExecuteNonQuery();
返回结果;
}
}
捕获(例外情况除外)
{
AddEventToEventLogTable(“DAL.DataBase.ParametersCommand()方法中的错误:”+ex.Message,1);
返回0;
投掷;
}
最后
{
闭合连接(参考连接);
}
}
专用静态void CloseConnection(参考SqlConnection conn)
{
如果(连接状态!=连接状态已关闭)
{
康涅狄格州关闭();
conn.Dispose();
}
}

您在哪里设置?您是否尝试过在没有@的情况下添加参数(在parameters.Add中)?例如,
command.Parameters.AddWithValue(“id”,“abc”)
^他说你需要
command.CommandText=query
,否则你的查询根本与command无关你说的
@password
-但你的意思是
@saltedPasswordHash
,对吗;您从DB收到的错误消息是什么?IMHO U具有唯一主键,并且已设置具有此值的行。Sou try change id作为“abc”以外的另一个字符串,OP表示非参数化查询可以正常工作。由于已为用户名插入了
abc
,如果为用户名设置了唯一键约束,则数据库可能不再允许
abc
。@Kaf-hmmm;有趣-但您可能会期望一个唯一的约束冲突作为例外,在这种情况下,我已经在使用完全相同的代码。我正在打开一个连接,用查询和连接创建一个SQLCommand,并执行相同的步骤。不知道为什么它不起作用对不起,我没有看到您使用了Add方法。它现在确实起作用了。我不知道为什么这是唯一的办法,但我很高兴它终于起作用了。非常感谢,无需调用
connection.Close()
如果您的
SqlConnection
对象处于使用块中,
Dispose()
将为您执行此操作。请注意,此处显示的
Add()
重载已被弃用一段时间。记录弃用的链接:if Add()
class Program
{
    static void Main(string[] args)
    {
        string connetionString = null;
        SqlConnection connection;
        SqlCommand command;
        string sql = null;

        connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
        sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
        connection = new SqlConnection(connetionString);

        try
        {
            connection.Open();
            Console.WriteLine(" Connection Opened ");
            command = new SqlCommand(sql, connection);                
            SqlDataReader dr1 = command.ExecuteReader();         

            connection.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Can not open connection ! ");
        }
    }
}
private void button1_Click(object sender, EventArgs e)
    {
        String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (@txtitemid,@txtitemname,@txtitemdesc,@txtitemqty)";
        try
        {
            using (SqlCommand command = new SqlCommand(query, con))
            {

                command.Parameters.AddWithValue("@txtitemid", txtitemid.Text);
                command.Parameters.AddWithValue("@txtitemname", txtitemname.Text);
                command.Parameters.AddWithValue("@txtitemdesc", txtitemdesc.Text);
                command.Parameters.AddWithValue("@txtitemqty", txtitemqty.Text);


                con.Open();
                int result = command.ExecuteNonQuery();

                // Check Error
                if (result < 0)
                    MessageBox.Show("Error");

                MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                con.Close();
                loader();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            con.Close();
        }
    }
public static string textDataSource = "Data Source=localhost;Initial 
Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";
public static bool ExtSql(string sql) {
    SqlConnection cnn;
    SqlCommand cmd;
    cnn = new SqlConnection(textDataSource);
    cmd = new SqlCommand(sql, cnn);
    try {
        cnn.Open();
        cmd.ExecuteNonQuery();
        cnn.Close();
        return true;
    }
    catch (Exception) {
        return false;
    }
    finally {
        cmd.Dispose();
        cnn = null;
        cmd = null; 
    }
}
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
    SqlConnection connection = new SqlConnection(ConnectionString);
    try
    {
        using (SqlCommand cmd = new SqlCommand(query, connection))
        {   // for cases where no parameters needed
            if (parameters != null)
            {
                cmd.Parameters.AddRange(parameters.ToArray());
            }

            connection.Open();
            int result = cmd.ExecuteNonQuery();
            return result;
        }
    }
    catch (Exception ex)
    {
        AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
        return 0;
        throw;
    }

    finally
    {
        CloseConnection(ref connection);
    }
}

private static void CloseConnection(ref SqlConnection conn)
{
    if (conn.State != ConnectionState.Closed)
    {
        conn.Close();
        conn.Dispose();
    }
}