❶ java連接資料庫的代碼
package mysql;
import java.sql.*;
/**
* @author xys
*/
public class ConnectMysql {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306/databaseName";
String user = "mysqluser";
String password = "password";
String driverClass = "com.mysql.cj.jdbc.Driver";
Connection connection = null;
Class.forName(driverClass);
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null) {
System.out.println("資料庫連接成功");
} else {
System.out.println("資料庫連接失敗");
connection.close();
}
return connection;
}
public void getResult() throws ClassNotFoundException, SQLException {
// 實例化 Statement 對象
Statement statement = getConnection().createStatement();
// 要執行的 Mysql 資料庫操作語句(增、刪、改、查)
String sql = "";
// 展開結果集資料庫
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
// 通過欄位檢索
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// 輸出數據
System.out.println("ID : " +id);
System.out.println("name :" + name);
}
// 完成後需要依次關閉
resultSet.close();
statement.close();
getConnection().close();
}
}