java链接mysql数据库并且写入数据并且解决写入数据库乱码问题
package Test0;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.DriverManager;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class Test00 {
static Connection conn;
static Statement st;
public static void main(String[] args) {
String path="/home/wjx/spider/baidu/";
File f = new File(path);
String[] names = f.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.indexOf(".txt") != -1;// 等于-1,表示不存在
}
});
for (String str : names)
insert(path+str);
}
public static Connection getConnection() {
Connection con = null; // 创建用于连接数据库的Connection对象
try {
Class.forName("com.mysql.jdbc.Driver");// 加载Mysql数据驱动
con = (Connection) DriverManager.getConnection( "jdbc:mysql://192.168.1.122/cgdb?user=cg&password=&useUnicode=true&characterEncoding=utf-8" );
//解决写入数据库乱码问题 http://blog.csdn.net/liuxueyongyu/article/details/2026788
//(Connection) DriverManager.getConnection("jdbc:mysql://172.27.35.8:3306/wjx", "root", "1314521");// 创建数据连接
} catch (Exception e) {
System.out.println("数据库连接失败" + e.getMessage());
}
return con; // 返回所建立的数据库连接
}
public static void insert(String path) {
try {
conn = getConnection(); // 首先要获取连接,即连接到数据库
st = (Statement) conn.createStatement(); // 创建用于执行静态sql语句的Statement对象
String usesql = "use cgdb";
st.execute(usesql);
int i=0;
InputStream in = new FileInputStream(path);
InputStreamReader ir = new InputStreamReader(in);
BufferedReader br = new BufferedReader(ir);
String target=null;
Pattern pattern = Pattern
.compile("^\\{(.+)\\}\\{(\\d+)\\}\\{(\\d+)\\}\\{(.+)\\}$");
&nbs