一、如下數據庫鏈接及操做實例java
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(); } } }