更新時間:2022-11-11 09:41:29 來源:動力節點 瀏覽991次
jsp連接MySQL數據庫的代碼是什么?動力節點小編來告訴大家。
1.下載驅動mysql-connector-java-*.*.*-bin.jar 放到WEB-INF/lib/下,記得重啟tomcat。
2.示例代碼如下。
String driverName="com.mysql.jdbc.Driver";
String userName="username";
String userPasswd="password";
String dbName="dbname";
String tableName="tablename";
String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn=DriverManager.getConnection(url);
Statement statement = conn.createStatement();
String sql="SELECT * FROM "+tableName;
ResultSet rs = statement.executeQuery(sql);
// get the result
ResultSetMetaData rmeta = rs.getMetaData();
// the the number of columns
int numColumns=rmeta.getColumnCount();
// out each field
while(rs.next()) {
out.print(rs.getString(1)+" ");
out.print("|");
out.print(rs.getString(2));
out.print("
");
}
out.print("
");
out.print("Operations on the DB is done.");
rs.close();
statement.close();
conn.close();
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習