如何将输出结果保存到数据库
package mypack;
import java.io.*;
import java.sql.*;
public class FILE {
public static void main(String[] args) throws
ClassNotFoundException,
SQLException {
// TODO Auto-generated method stub
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //加载JDBC驱动
String dbURL = "jdbc:sqlserver://127.0.0.1:1433; DatabaseName=bbs"; //连接服务器和数据库test
String userName = "1234"; //默认用户名
String userPwd = "1234"; //密码
File file = new File("E:\\log.log");//获得文件
try {
int count=0;
Class.forName(driverName);
Connection con =java.sql.DriverManager.getConnection(dbURL, userName, userPwd);
Statement stmt = con.createStatement();
String sql = "insert into log(pv) values('count')";
stmt.executeUpdate(sql);
System.out.println("Connection Successful!");
FileReader fr = new FileReader(file);//读取文件
@SuppressWarnings("resource")
BufferedReader br = new BufferedReader(fr);//字符输入流化
String str;
while((str=br.readLine())!=null)
{
String[] s=str.split(",");
count++;
if(!str.trim().isEmpty())
System.out.println(s[4]);
}
stmt.close();
con.close();
System.out.println("文件共有"+count+"行");
} catch (
IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我要怎么才能把COUNT这个值存进数据库,而不是存COUNT这个字符,新手求大神稍微指点下
------解决方案--------------------这个很简单,你要用预编译语句对象:PreparedStatement,然后动态设置参数,代码大概是这样:
//先执行读取文件获得Count的代码,得到你的int count;
int count=0; //假设这是你得到的文件count数
Connection con=null;
PreparedStatement ps=con.prepareStatement("insert into log(pv) values(?)"); //用问号占位
ps.setInt(0, count); //给第1个问号设置参数为count
ps.executeUpdate();
------解决方案--------------------用连接符号连接一下;
String sql = "insert into log(pv) values('"+count+"')";