如何将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()

}

}

}

就是写文件啊,循环list string str = Guid.NewGuid().ToString()string strPath = "C:\\Program Files\\" + str + ".xls"FileStream fs = File.Create(strPath)StreamWriter sw = new StreamWriter(fs, Encoding.Unicode)string strLine = ""// 写入列标题 for (int i = 0i <colNames.Lengthi++) { string[] col = colNames[i].Split('=')strLine = strLine + col[1].ToString() + Convert.ToChar(9)} sw.WriteLine(strLine)strLine = ""// 写入报表数据 for (int i = 0i <dt.Rows.Counti++) { // for (int j = 0j <colNames.Lengthj++) { string[] col = colNames[j].Split('=')strLine = strLine + dt.Rows[i][col[0]].ToString() + Convert.ToChar(9)} sw.WriteLine(strLine)strLine = ""} sw.Close()fs.Close()

请注意看如下代码:

public List getObject(String sql, Object[] object) { //sql执行语句,object是你sql语句里面参数

List list = new ArrayList()

Connection con = null

PreparedStatement pre = null

ResultSet rs = null

try{

con = C3P0Util.getInstance().getConnection()//这是你获得数据库连接,你把这里改成调用你自己写的jdbc方法

pre = con.prepareStatement(sql)//执行sql语句

if(object!=null){

for(int i=0i<object.lengthi++){

pre.setObject(i+1, object[i])//给sql里面的参数进行赋值

}

}

rs = pre.executeQuery()

while(rs.next()){

Users u = new User()


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

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

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

发表评论

登录后才能评论

评论列表(0条)

保存