代码:
package com.hzjxy.jdbc;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class to_csdn {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/student_data";//连接到自己的数据库,我链接的数据库为student_data
String user = "root";//数据库登录用户名
String password = "root";//数据库登录密码
String sql_name = "borrow1";//需要插入的表名
String csv_path = "D:\\pcham\\borrow.csv";//与插入表数据对应的csv文件路径
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
String sql_col = "select * from "+sql_name+" where 1 = 2";
rs = stmt.executeQuery(sql_col);
ResultSetMetaData metaData = rs.getMetaData();
int col = metaData.getColumnCount();
String col_name = "";
String type = "";
for(int i=1; i <= col; i++) {
if(i == 1)col_name += metaData.getColumnName(i);
else col_name += ","+metaData.getColumnName(i);
if(i == 1)type += metaData.getColumnTypeName(i);
else type += " " + metaData.getColumnTypeName(i);
}
String col_type[] = type.split(" ");
try {
BufferedReader reader = new BufferedReader(new FileReader(csv_path));
reader.readLine();
String line = null;
while((line=reader.readLine())!=null){
String item[] = line.split(",");
String values = "";
for(int i=0; i<item.length; i++) {
if(col_type[i].equals("INT") || col_type[i].equals("DECIMAL")) {
if(i == 0)values += "values(" + item[i];
else {
values += ","+item[i];
}
}
else{
if(i == 0)values += "values(" + "'" + item[i] + "'";
else {
values += "," + "'" + item[i] + "'";
}
}
}
values += ")";
String sql = "insert into "+sql_name+"(" + col_name + ")" + " " + values;
int count = stmt.executeUpdate(sql);
if(count == 1)System.out.println("插入成功");
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
if(rs!=null)
{
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}if(stmt!=null)
{
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}if(conn!=null)
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
注意:
对于方法execute、executeUpdate、executeQuery的使用范围:
execute:增、删、改、查
executeUpdate:增、删、改
executeQuery:查