标签:
要在java对数据库做任何操作,第一件事当然是获取数据库连接,笔者是通过配置文件的形式加载数据库信息的,配置文件名为db.properties,内容如下
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/customermanage
username=root
password=root
ps:properties中的内容均为键值对形式,不需要用到引号
接下来是DBUtil类,获取配置,得到连接
package com.cherry.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.ResourceBundle;
public class DBUtils {
static String driver;
static String url;
static String username;
static String password;
static {
try {
// Class.forName("com.mysql.jdbc.Driverr");
// DriverManager.getConnection("jdbc:mysql://localhost:3306/customermanage",
// "root", "root");
ResourceBundle rb = ResourceBundle.getBundle("db");
driver = rb.getString("driver");
Class.forName(driver);
url = rb.getString("url");
username = rb.getString("username");
password = rb.getString("password");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
public static void releaseRes(ResultSet rs, PreparedStatement ps,
Connection conn) throws SQLException {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
}
先说说批处理操作类
package com.cherry.batch;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.cherry.utils.DBUtils;
public class BatchSQL {
public static void main(String[] args) throws SQLException {
Connection conn= DBUtils.getConn();
String sql="insert into des value(?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
for ( int i=0;i<10000 ;i++) {
ps.setString(1, "name"+i);
ps.setString(2, "des"+i);
ps.addBatch();
if(i%100==0){
ps.executeBatch();
ps.clearBatch();
}
}
}
}
再看大文本或图片类型的存储
package com.cherry.batch;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.UUID;
import com.cherry.utils.DBUtils;
public class TextSQL {
public static void main(String[] args) {
try {
Connection connection = DBUtils.getConn();
String sql = "insert into des values(?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, UUID.randomUUID().toString());
File file = new File("f://test.txt");
Reader reader = new FileReader(file);
//这里不一定要强转,看你的mysql驱动版本,总之不转不行就转个试试
ps.setCharacterStream(2, reader, (int)file.length());
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
另外,注意导包,这里所有的数据库操作类所导的都是java.sql下的,想想也知道,面向接口编程的Java君,肯定是使用sql包的(普适性),因为mysql/sqlserver/orcale这些都是实现类,用他们肯定不合适。
标签:
原文地址:http://blog.csdn.net/illusion_1202/article/details/51330588