#使用JDBC訪問資料庫,實現web與資料庫的通訊
阿新 • • 發佈:2018-12-18
//驅動程式名
String driverName = "com.mysql.jdbc.Driver";
//資料庫使用者名稱
String userName = "root";
//密碼
String userPasswd = "12345678";
//資料庫名
String dbName = "testweb";
//表名
String tableName = "person";
//聯結字串
String url = "jdbc:mysql://localhost:3306/" + dbName + "?user="
+ userName + "&password=" + userPasswd;
//需要try-catch,註冊資料庫
Class.forName("com.mysql.jdbc.Driver");
//獲取資料庫連線,也可以Connection connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/testWeb" ,“root”,“12345678”);
Connection connection = DriverManager.getConnection(url);
//獲取statement
Statement statement = connection.createStatement();
String sql = "select * from " + tableName;
//String sql = "insert into person (name,age,sex) values ('孫悟空','55','猴')";
//String sql = "delete from person where name='孫悟空'";
//String sql = "update person set name='陽陽' where description='女神'";
//執行查詢語句
ResultSet rs = statement.executeQuery(sql);
//執行新增刪除修改語句
//statement.executeUpdate(sql);
...
//查詢的時候用re.next()遍歷,out列印rs,注意getString(1)是從1開始而不是0
<%
while (rs.next()) {
out.print(rs.getString(1));
out.print(rs.getString(2));
%>
//前面通過ResultSet使用了Query後面的rs就要close(),statement和connection要記得關閉
rs.close();
statement.close();
connection.close();
注意connection一定要關閉,否則會一直佔用連線池
然後,記得新建專案的時候要匯入相關jar包:Apache的,jdbc的(mysql-connector-java-5.1.47.jar)。
