如何将List集合插入到数据库中

如何将List集合插入到数据库中,第1张

可以用QueryRunner的batch方法

public class Test {

private static final String DRIVER_CLASS_NAME = ""

private static final String JDBC_URL = ""

private static final String USER = ""

private static final String PASSWORD = ""

public static void main(String[] args) {

int count = 10// 插入记录的数目

Object[][] params = new Object[count][]

for (int i = 0i <counti++)

// 将每条记录的数据插入数组

params[i] = new Object[] { "", "", "" }

batch(params)

}

public static Connection getConnection() {

Connection conn = null

try {

Class.forName(DRIVER_CLASS_NAME)

conn = DriverManager.getConnection(JDBC_URL, USER, PASSWORD)

return conn

} catch (Exception e) {

return null

}

}

public static void batch(Object[][] params) {

QueryRunner queryRunner = new QueryRunner(true)

String sql = "INSERT INTO TABLE_NAME VALUES (?,?,?)"

try {

queryRunner.batch(getConnection(), sql, params)

} catch (SQLException e) {

e.printStackTrace()

}

}

}

参考代码及说明如下:

SqlConnection conn = new SqlConnection()

        conn.Open()

        SqlTransaction tran = conn.BeginTransaction()

        try

        {

            foreach()

            {

                string sql=""

                SqlCommand cmd=new SqlCommand(sql,conn,tran)

                SqlParameter[] pars=new SqlParameter[]{

                    new SqlParameter("",value),

                    ...

                }

                //cmd.Parameters的AddRange方法是增加一个参数的数组

                cmd.Parameters.AddRange(pars)

                //ExecuteNonQuery()是update,delete ,insert影响行数

                cmd.ExecuteNonQuery()                    

            }

            tran.Commit()

        }catch

        {

            tran.Rollback()

        }

        finally

        {

            conn.Close()

        }


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/6424609.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-22
下一篇 2023-03-22

发表评论

登录后才能评论

评论列表(0条)

保存