java把txt文件中的数据导入mysql数据库

来源:互联网 发布:朝鲜战争知乎 编辑:程序博客网 时间:2024/05/18 01:03

import java.io.*;
import java.sql.*;
public class BatImport
{
 public static void main(String args[]) throws Exception
 {
  File f = new File("data.txt");
  BufferedReader bf = new BufferedReader(new FileReader(f));
  String str;
  String driver = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost/jxb";
  String user="dbuser";
  String password="1234";
  
  try{
  Class.forName(driver);
  System.out.println("123");
  Connection conn = DriverManager.getConnection(url,user,password);
  System.out.println(conn.isClosed()+"123");
  Statement st = conn.createStatement();
  String sql;
  while(null!=(str=bf.readLine()))
  {
   String s[]=str.split(",");
   sql="insert into stu values('"+s[0]+"','"+new String(s[1].getBytes("gb2312"),"ISO-8859-1")+"','"+s[2]+"')";

//字符编码转换
   int i=st.executeUpdate(sql);
   System.out.println(i+"条记录执行成功");
  }
  conn.close();
  }
  catch(ClassNotFoundException e) {
            System.out.println("Sorry,can`t find the Driver!");
            e.printStackTrace();
   }
   catch(SQLException e) {
            e.printStackTrace();
           }
     catch(Exception e) {
            e.printStackTrace();
   }
 }
}

dta.txt的内容(编码方式是gb2312)

zhangsan,男,98
lisi,男,89
wangwu,女,78

这里需要注意三点:我在做这个实验的时候,提示驱动注册失败.原因是我下载的驱动和mysql数据库的版本不吻合

第二个就是注意编码的问题,我的mysql编码是latin1也就是ISO-8859-1.因此再出入汉字时需要转码,同样的,取出来时也需要转码。

第三个就是mysql的驱动程序加载之后会自动注册自己(静态代码块,装载类之后【类的装载,连接和初始化,在初始化阶段注册】)