java讀寫操作
/*從txt中讀取文件參數到數據庫中查詢,將查詢結果從新寫入到文本文件中*/
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class we {
static String url;
static String name;
static String password;
static String id1;
static String temp ;
static{
Properties cfg=new Properties();
InputStream in=we.class.getClassLoader().getResourceAsStream("db.properties");
try {
cfg.load(in);
url=cfg.getProperty("url");
name=cfg.getProperty("name");
password=cfg.getProperty("password");
id1=cfg.getProperty("id1");
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
BufferedWriter bw=new BufferedWriter(new FileWriter("testsql.txt",true));
BufferedReader br=new BufferedReader(new FileReader("read.txt"));
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection(url,name,password);
String sql="select id,name,phone from yrd_users where phone=?";
PreparedStatement psmt=conn.prepareStatement(sql);
String s=null;
while((s=br.readLine())!=null) {
System.out.println(s);
psmt.setString(1, s);
ResultSet res=psmt.executeQuery();
while(res.next()) {
String id=res.getString("id");
String name=res.getString("name");
String phone=res.getString("phone");
temp += phone+" "+ name +" "+id+"\r\n";
}
}
bw.write(temp);
conn.close();
bw.close();
br.close();
}
}
java讀寫操作