복붙노트

[SQL] SQL 삽입 쿼리 C #을 사용

SQL

SQL 삽입 쿼리 C #을 사용

내가 해결하기 위해 노력하고있는 순간에 문제가 있어요. 난 그냥 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);

여전히 작동하지 않는 나는 위의 코드에 아무것도 잘못을 찾을 수 없습니다.

해결법

  1. ==============================

    1.난 당신이 데이터베이스에 연결되어 가정 당신은 C #을 사용 삽입 매개 변수를 할 수 없습니다.

    난 당신이 데이터베이스에 연결되어 가정 당신은 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!");
        }
    }
    
  2. ==============================

    2.시험

    시험

    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();
        connection.Close();
    }
    
  3. ==============================

    3."일어나지 않았다 내 삽입"를로 (표현을 사용하는 경우 특히) 가장 일반적인 실수는 다음과 같습니다 잘못된 파일을보고.

    "일어나지 않았다 내 삽입"를로 (표현을 사용하는 경우 특히) 가장 일반적인 실수는 다음과 같습니다 잘못된 파일을보고.

    당신이 (강하게 부착보다는) 파일 기반 특급 프로젝트 폴더에 다음 파일을 사용하는 경우 (예를 들어, C를 : \ DEV \ MyProject를 \ mydb.mbd) 프로그램에서 사용하지 않는 파일입니다. 당신이 빌드 할 때 해당 파일이 복사됩니다 - 예를 들어 C에 : \ DEV \ MyProject를 \ 빈 \ 디버그 \ mydb.mbd; C의 맥락에서 프로그램이 실행 : \ dev에 \ MyProject를 \ 빈 \ 디버그 \, 그리고 당신이 편집이 실제로 발생하는지 볼 필요가 여기에있다 그래서. 확실히 확인하려면 다음을 (를 삽입 후) 응용 프로그램 내부의 데이터에 대한 쿼리를.

  4. ==============================

    4.

    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);
            }
        }
    
  5. ==============================

    5.

    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();
            }
        }
    
  6. ==============================

    6.

    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; 
        }
    }
    
  7. ==============================

    7.난 그냥 아무 대답이 재사용 방법 여기에 없다, 그것을위한 재사용 가능한 방법을 썼다하지 공유 ... 여기 내 현재 프로젝트의 코드입니다 왜 그렇게 :

    난 그냥 아무 대답이 재사용 방법 여기에 없다, 그것을위한 재사용 가능한 방법을 썼다하지 공유 ... 여기 내 현재 프로젝트의 코드입니다 왜 그렇게 :

    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();
        }
    }
    
  8. ==============================

    8.

    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 ! ");
            }
        }
    }
    
  9. from https://stackoverflow.com/questions/19956533/sql-insert-query-using-c-sharp by cc-by-sa and MIT license