java txt数据库_java 将TXT中数据插入数据库

在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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值