JDBCUTIL
可能用到的依赖:
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
代码:
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* 1. 获取数据源
* 2. 获取连接对象
* 3. 返回dbutils的QueryRunner对象
*/
public class JDBCUtil {
private static ComboPooledDataSource dataSource = null;
static {
dataSource = new ComboPooledDataSource();
}
/**
* 1.获取数据库连接对象 (事务),这个连接对象需要手动释放
* @return
*/
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 2.获取dbutils的QueryRunner对象(非事务),资源会自动释放
* @return
*/
public static QueryRunner getQueryRunner() {
return new QueryRunner(dataSource);
}
}
/*
* json依赖
* <dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
*/
public class JsonTOmysql {
public static void main(String[] args) {
String path="C:\\Users\\WANG\\Desktop\\spark项目\\userInfo.json";
try {
try {
readFromFile(path);
} catch (SQLException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readFromFile(String path) throws IOException, SQLException {
BufferedReader br = new BufferedReader(
new FileReader(path));
String line = null;
while ((line = br.readLine()) != null) {
JSONObject responseJson = JSONObject.fromObject(line);
Object user_id = responseJson.get("user_id");
Object username = responseJson.get("username");
Object name = responseJson.get("name");
Object age = responseJson.get("age");
Object professional = responseJson.get("professional");
Object city = responseJson.get("city");
Object sex = responseJson.get("sex");
String sql = "insert into user_info values (?,?,?,?,?,?,?)";
Object [] params = {user_id,username,name,age,professional,city,sex};
QueryRunner qr = JDBCUtil.getQueryRunner();
qr.update(sql,params);
}
br.close();
}
}