在TXT文本中的内容如下:
001,小红,
002,小芳,
存放位置为G:/test.txt
数据库的testInfo表中有两个字段,id,name要将TXT中的内容插入数据库
代码如下
public static void main(String[] args) {
insert();
}
public static void insert()
{
InputStreamReader inputReader = null;
BufferedReader bufferReader = null;
OutputStream outputStream = null;
try
{
conn = getConnection();//打开连接
try
{
InputStream inputStream = new FileInputStream("G:/test.txt"); //打开txt
inputReader = new InputStreamReader(inputStream);
bufferReader = new BufferedReader(inputReader);
// 读取一行
String line = null;
StringBuffer strBuffer = new StringBuffer();
while ((line = bufferReader.readLine()) != null)
{
strBuffer.append(line+ "\n");
String [] strs=line.split(",");
String sql="insert into TestInfo(id,name) values( '"+strs[0]+"','"+strs[1])";
st = (Statement) conn.createStatement();
int count = st.executeUpdate(sql);
System.out.println("向表中插入 " + count + " 条数据");
}
}
catch(IOException e)
{
}
}
catch(SQLException e)
{
System.out.println("插入数据失败" + e.getMessage());
}
}
public static Connection getConnection()
{
Connection con = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
//连接数据库库,设置characterEncoding=UTF-8防止乱码
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hotelATMDb?characterEncoding=UTF-8", "root", "123456");
}
catch(Exception e)
{
System.out.println("数据库连接失败" + e.getMessage());
}
return con;
}