1、以下数据库连接及操作实例
package properties;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class test {
public static void main(String[] args) {
/*FileWriter fw;
fw = new FileWriter("tt.txt",true);//加上 true参数,代表是往这个文件中添加 内容,不是覆盖原文件的内容
fw.write("this is my");
fw.write("stu");
fw.write("dent");
fw.write(".");
fw.write("txt");
fw.write("这是我的文件");
fw.close();*/
/*URL aurl=new URL("http://www.googel.com:80");
System.out.println("protocol="+aurl.getProtocol());
System.out.println("Authority="+aurl.getAuthority());
System.out.println("Host="+aurl.getHost());
System.out.println("Port="+aurl.getPort());*/
add_update_del("update t_Accepted_Cert_Info t set t.custname='颜丽' where t.mobileno ='13536703748'");
query("select * from t_Accepted_Cert_Info info where info.mobileno ='13536703748'");
}
public static Properties getProperties() {
Properties prop = new Properties();//Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串
try {
// /加载属性列表
//InputStream in = new BufferedInputStream(new FileInputStream(
//"D:\\myselenium\\config.properties"));
//读取当前工程下的配置文件
InputStream in =test.class.getResourceAsStream("/properties/config.properties");// getResourceAsStream查找具有给定名称的资源,返回一个InputStream对象
prop.load(in);//从流中加载
return prop;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Connection getConnection(){
Connection conn=null;
String driverName=getProperties().getProperty("orcal.driverName");
String url=getProperties().getProperty("PA18dburl");
String username=getProperties().getProperty("PA18dbuser");
String pwd=getProperties().getProperty("PA18sdbpsw");
try {
Class.forName(driverName);
conn=DriverManager.getConnection(url,username,pwd);
if (conn!=null){
System.out.println("数据库连接成功");
}
return conn;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static void add_update_del(String sql){
Connection conn=getConnection();
int x;
try {
Statement st=conn.createStatement();
x = st.executeUpdate(sql);
System.out.println("操作成功"+x);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void query(String sql){
try{
Connection conn=getConnection();
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery(sql);
//当返回的结果集不为空时,并且还有记录时
while(rs!=null && rs.next()){
int id=rs.getInt(1);//获取当前记录的第一个字段的值
String name=rs.getString("custname");
String addr=rs.getString("addr");
System.out.println("id"+id+"\t"+"name"+name+"\t"+"addr"+addr+"\t");
}
}catch(Exception e){
e.printStackTrace();
}
}
}