C# 批量插入Mysql数据的实例代码

发布时间:2020-12-11编辑:脚本学堂
本文分享一例c#操作mysql数据库的代码,用于批量插入mysql数据,有需要的朋友可以参考下。

本节内容:
一例批量插入mysql数据的c#代码。

例子:
 

复制代码 代码示例:

public void loadData(Connection connection)
{
    long starTime = System.currentTimeMillis();
 
    String sqlString = "load data local infile ? into table test";
    PreparedStatement pstmt;
    try {
        pstmt = connection.prepareStatement(sqlString);
        
        pstmt.setString(1, "tfacts_result");
        
        pstmt.executeUpdate();
        
        pstmt.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    
    long endTime = System.currentTimeMillis();
    
    System.out.println("program runs " + (endTime - starTime) + "ms");
 
}

//批量插入mysql数据
public static void mysql_batch(string sqlStr,int point)
        {
            string sql = "insert into test(node1, node2, weight) values(?, ?, ?)";

            Connection conn = getConn("mysql");
            conn.setAutoCommit(false);
            //clear(conn);
            try
            {
                PreparedStatement prest = conn.prepareStatement(sql);
                //long a = System.currentTimeMillis();
                for (int x = 1; x <= count; x++)
                { // www.jb200.com
                    prest.setInt(1, x);
                    prest.setString(2, "张三");
                    prest.addBatch();
                    if (x % point == 0)
                    {
                        prest.executeBatch();
                        conn.commit();
                    }
                }
                prest.close();
                //long b = System.currentTimeMillis();
                //print("MySql批量插入10万条记录", a, b, point);
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
            finally
            {
                close(conn);
            }