import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class ShuangSeQiuToDatabase {
public static void main(String [] args) throws IOException{
String url="jdbc:mysql://localhost:3306/mydatabase";
String user="root";
String pwd = "12345";
//加载数据库
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
Connection con;
Statement st = null;
//连接数据库
try {
con = DriverManager.getConnection(url, user,pwd );
st = con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
System.exit(0);
}
//打开数据文件
FileReader f = new FileReader("d:\\data.csv");
BufferedReader bfr = new BufferedReader(f);
String line;
while((line = bfr.readLine())!=null){
//每行有8个数据,用逗号隔开的,这里把它们分开暂时存在tem里面
String[] tem = line.split(",");
String sql = "insert into shuangseqiu (tem[0],tem[1],tem[2],tem[3],tem[4],tem[5],tem[6],tem[7],)";
try {
st.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
数据库连接成功。
我想问的问题就是这一块:
String sql = "insert into shuangseqiu (tem[0],tem[1],tem[2],tem[3],tem[4],tem[5],tem[6],tem[7],)";
try {
st.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
把tem[i]放到“”里边作为字符串就不是它的值了,而直接是tem[i]作为字符串插入进去,所以出错,怎么把tem[i]的值显现出来呢?
æè
StringBuffer sb = new StringBuffer();
sb.append("insert into shuangseqiu (");
for(int i = 0; i < tem.length; i++){
if(tem.length -1 == i){
sb.append(tem[i]+")");
}else{
sb.append(tem[i]+",");
}
}
String sql = "insert into shuangseqiu values("+tem[0]+","+tem[1]+","+tem[2]+","+tem[3]+","+tem[4]+","+tem[5]+","+tem[6]+","+tem[7]+","+")";
对楼主的建议:
1、字符串的拼接最好使用stringbuffer或者stringbuild,这两者是内容可变的,效率相对高些。
2、上面的语句最好把字段名写上,如:insert into shuangseqiu(字段1,字段2...) values()。
有问题欢迎提问,满意请采纳!
是String ?
那就是那样的呀
String sql = "insert into shuangseqiu ('"+tem[0]+"', '"+tem[1]+"','"+tem[2]+"','"+tem[3]+"','"+tem[4]+"','"+tem[5]+"','"+tem[6]+"','"+tem[7]+"')";
或者,使用PreparedStatement , 然后用参数
PreparedStatement pst = con.prepareStatement("insert into shuangseqiu(?, ?, ?, ?, ?, ?, ?)");
for(int i=0; i<tem.length; i++)
pst.setString(i+1, tem[i]);
pst.executeUpdate();