//运用Java JDBC编写程序向MySQL中插入数据
package operateRDBMS;
import java.util.*;
import java.io.*;
import java.sql.*;
public class InsertMySQL
{
private String driver;
private String url;
private String user;
private String pass;
public void initParam(String paramFile)throws Exception
{
// 使用Properties类来加载属性文件
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
// 加载驱动
Class.forName(driver);
}
public long insertUsePrepare()throws Exception
{
long count = 0;
try(
FileReader fr = new FileReader("/home/hadoop/WorkHbase/test10wan.txt");
BufferedReader br = new BufferedReader(fr);
// 获取数据库连接
Connection conn = DriverManager.getConnection(url
, user , pass);
// 使用Connection来创建一个PreparedStatement对象
PreparedStatement image = conn.prepareStatement(
"insert ignore into image values(?,?)");
PreparedStatement patient = conn.prepareStatement(
"insert ignore into patient values(?,?,?,?)");
PreparedStatement hospital = conn.prepareStatement(
"insert ignore into hospital values(?,?)");
PreparedStatement doctor = conn.prepareStatement(
"insert ignore into doctor values(?,?)");
PreparedStatement study = conn.prepareStatement(
"insert ignore into study values(?,?,?,?,?)");
PreparedStatement imag_stu = conn.prepareStatement(
"insert ignore into imag_stu values(?,?)");
)
{
String line = new String();
while((line = br.readLine())!=null){
String[] split= line.split(", ");
String hid = split[0];
String hname = split[1];
String part = split[2];
String did = split[3];
String dname = split[4];
String pid = split[5];
String pname = split[6];
String psex = split[7];
String pdob = split[8];
String sdate = split[9];
String sid = split[10];
String url = split[11];
image.setString(1 , url);
image.setString(2, part);
patient.setString(1,pid);
patient.setString(2,pname);
patient.setString(3,psex);
patient.setString(4,pdob);
hospital.setString(1,hid);
hospital.setString(2,hname);
doctor.setString(1,did);
doctor.setString(2,dname);
study.setString(1,sid);
study.setString(2, sdate);
study.setString(3, hid);
study.setString(4,did);
study.setString(5,pid);
imag_stu.setString(1, url);
imag_stu.setString(2, sid);
image.executeUpdate();
patient.executeUpdate();
hospital.executeUpdate();
doctor.executeUpdate();
study.executeUpdate();
imag_stu.executeUpdate();
count ++;
}
}
catch (IOException ioe){
ioe.printStackTrace();
}
return count;
}
public static void main(String[] args) throws Exception
{
long start;
start = System.currentTimeMillis();
InsertMySQL pt = new InsertMySQL();
pt.initParam("/home/hadoop/mysql.ini");
long count = pt.insertUsePrepare();
System.out.printf("Time used: %d",(System.currentTimeMillis()-start));
System.out.printf("\nTotal lines: %d",count);
}
}
运用Java JDBC编写程序向MySQL中插入数据
最新推荐文章于 2024-06-21 14:47:02 发布