import java.sql.*;</p><p>public class DBTest2<br />{<br />String url = "jdbc:mysql://localhost:3306/";<br />String user = "root";<br />String passwd = "root";<br />public DBTest2()throws ClassNotFoundException<br />{<br />Class.forName("com.mysql.jdbc.Driver");<br />}<br />public static void main(String[] args)<br />{<br />}<br />}
<br />import java.io.*;<br />import java.sql.*;<br />public class ConnectionDemo<br />{<br />public static void main(String[] args)<br />{<br />String sql1 = "select * from a1";<br />String sql2 = "insert into a1(aa,bb)values(null,'aaa')";<br />try{<br />DBSource dbsource = new SimpleDBSource();<br />Connection conn = dbsource.getConnection();<br />Statement stmt = conn.createStatement();<br />ResultSet rs = stmt.executeQuery(sql1);<br />ResultSetMetaData rmeta = rs.getMetaData();<br />int numColumns = rmeta.getColumnCount();<br />System.out.println(numColumns);<br />//rs.next();<br />//System.out.println(rs.getString(1));<br />//System.out.println();<br />while(rs.next())<br />{<br />//rs.next();<br />//String str1 = rs.getString(0);<br />//int a1 = rs.getInt(0);<br />//System.out.println(str1);<br />//System.out.println(a1);<br />for(int i = 0;i<numColumns;i++)<br />{<br />String sTemp = rs.getString(i+1);<br />System.out.println(sTemp + " ");<br />}<br />System.out.println();</p><p>}<br />for(int i=0;i<10000;i++)<br />{<br />stmt.executeUpdate(sql2);<br />}<br />if(!conn.isClosed())<br />{<br />System.out.println("資料庫連接已開啟");<br />}<br />dbsource.closeConnection(conn);<br />if(conn.isClosed())<br />{<br />System.out.println("資料庫連接已關閉");<br />}<br />/*}catch(IOException e){<br />e.printStackTrace();*/<br />}catch(ClassNotFoundException e){<br />e.printStackTrace();<br />}catch(SQLException e){<br />e.printStackTrace();<br />}<br />}<br />}</p><p>import java.sql.*;</p><p>public interface DBSource{<br />public Connection<br />getConnection()throws SQLException;<br />public void<br />closeConnection(Connection conn)throws SQLException;<br />}</p><p>import java.util.*;<br />import java.sql.*;<br />import java.io.*;</p><p>public class SimpleDBSource implements DBSource<br />{<br />String url;<br />String user;<br />String passwd;<br />public SimpleDBSource()throws ClassNotFoundException<br />{<br />url = "jdbc:mysql://localhost:3306/demo";<br />user = "root";<br />passwd = "root";<br />Class.forName("com.mysql.jdbc.Driver");<br />}<br />public Connection<br />getConnection()throws SQLException<br />{<br />return DriverManager.getConnection(url,user,passwd);<br />}<br />public void<br />closeConnection(Connection conn)throws SQLException<br />{<br />conn.close();<br />}<br />}