31

我目前正在尝试解决一个问题。我只是尝试在 C# 的帮助下访问数据库并插入一些值

我尝试过的事情(工作)

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

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

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();

谁能告诉我我做错了什么?

亲切的问候

编辑:

在另一行中,我正在创建一个新的 SQL 命令

var cmd = new SqlCommand(query, connection);

仍然无法正常工作,我在上面的代码中找不到任何错误。

4

8 回答 8

55

我假设您已经连接到您的数据库,并且您不能使用 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!");
    }
}
于 2013-11-13T14:55:57.300 回答
10

尝试

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();
}
于 2013-11-13T14:48:21.537 回答
5

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

如果您使用的是基于文件的 express(而不是强附加),那么项目文件夹中的文件(例如c:\dev\myproject\mydb.mbd不是您的程序中使用的文件。当您构建时,该文件被复制 - 例如到c:\dev\myproject\bin\debug\mydb.mbd; 您的程序在 的上下文中执行c:\dev\myproject\bin\debug\,因此您需要在这里查看编辑是否实际发生。确定检查:查询应用程序内的数据(插入后)。

于 2013-11-13T14:47:04.420 回答
2
static SqlConnection myConnection;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        myConnection = new SqlConnection("server=localhost;" +
                                                      "Trusted_Connection=true;" +
             "database=zxc; " +
                                                      "connection timeout=30");
        try
        {

            myConnection.Open();
            label1.Text = "connect successful";

        }
        catch (SqlException ex)
        {
            label1.Text = "connect fail";
            MessageBox.Show(ex.Message);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
        String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
        SqlCommand sqlcom = new SqlCommand(st, myConnection);
        try
        {
            sqlcom.ExecuteNonQuery();
            MessageBox.Show("insert successful");
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
于 2015-11-02T08:38:10.720 回答
0
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();
        }
    }
于 2018-04-03T12:50:38.507 回答
0
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; 
    }
}
于 2018-07-09T18:35:28.270 回答
0

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

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();
    }
}
于 2018-07-12T11:03:47.887 回答
-2
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 ! ");
        }
    }
}
于 2016-05-09T15:21:15.247 回答