Multiple Insert statements in one connection

前端 未结 4 1714
南旧
南旧 2021-01-24 00:05

I need some tips on how to do this better, I am inserting multiple queries with using one connection.

I understand this is not good programming, especi

4条回答
  •  北海茫月
    2021-01-24 00:33

    You are executing only the query2 not the query3 and query4 command text

    OpenConnection2();
    command.Connection = connection;
    
    command.CommandText = query2;
    int c = command.ExecuteNonQuery();
    
    command.CommandText = query3;
    c = command.ExecuteNonQuery();
    
    command.CommandText = query4;
    c = command.ExecuteNonQuery();
    connection.Close();
    

    Said this, really you should use parameters also if you don't have concerns of Sql Injection because your code will be more clear and you don't need to worry about parsing strings to replace quotes, prepare the correct string for datetime field and use the correct decimal point character for floating point values

    Another optimization is through the using statement.
    In this case your OpenConnection2 should return the OleDbConnection created and opened and no need to use a global connection object (Always a bad practice also with file based databases)

    public OleDbConnection OpenConnection2()
    {
        OleDbConnection connection = new OleDbConnection("");
        connection.Open();
        return connection;
    }
    

    and then in your code you will be able to use the using statement that will ensure the correct close and dispose of the connection when is no more needed

    using(OleDbConnection cn = OpenConnection2())
    using(OleDbCommand command = new OleDbCommand())
    {
        command.Connection = connection;
        command.CommandText = query2;
        int c = command.ExecuteNonQuery();
    
        command.CommandText = query3;
        c = command.ExecuteNonQuery();
    
        command.CommandText = query4;
        c = command.ExecuteNonQuery();
    } // here the connection will be closed and disposed 
    

    As a last note, if you are running these queries against an MS Access Database then you need to execute them one by one because there is no support for multistatement

提交回复
热议问题