SQL Insert Query Using C#

后端 未结 8 1702
长情又很酷
长情又很酷 2020-11-27 17:24

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#

The things I tried (worked)

相关标签:
8条回答
  • 2020-11-27 18:15
    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; 
        }
    }
    
    0 讨论(0)
  • 2020-11-27 18:22

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

    Updated:

    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!");
        }
    }
    
    0 讨论(0)
提交回复
热议问题