導航:首頁 > 編程語言 > java中讀取資料庫中數據

java中讀取資料庫中數據

發布時間:2025-09-10 15:22:19

java中怎麼獲取mysql資料庫的數據

用JDBC連接資料庫,然後用sql語句。要導入mysql的驅動包。
import java.sql.*;

public class TestMySql {
static Connection con = null; // 聲明Connection對象
static Statement sql = null;
static ResultSet res = null;

public static void main(String[] args) {
TestMySql c = new TestMySql();
con = c.getConnection();
try {
sql = con.createStatement();
res = sql.executeQuery("select * from dept");
//sql語句,我資料庫里有張dept表

while (res.next()) {//輸出結果
System.out.print(res.getString(1) + "<——>");
System.out.print(res.getString(2) + "<——>");
System.out.print(res.getString(3) );
System.out.println();
}

} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (res != null) {
res.close();
res =null;
}
if (sql != null) {
sql.close();
sql =null;
}
if (con != null) {
con.close();
con =null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}

}

public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
// 載入oracleJDBC驅動
System.out.println("資料庫驅動載入成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {// 通過訪問資料庫的URL獲取資料庫連接對象
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydata", "root", "qwer1234");
//mydata為mysql名字

System.out.println("資料庫連接成功");
} catch (SQLException e) {
e.printStackTrace();
}
return con; // 按方法要求返回一個Connection對象
}

}

閱讀全文

與java中讀取資料庫中數據相關的資料

熱點內容
pdf轉cad格式轉換器 瀏覽:363
華碩電腦磁碟加密怎麼解決 瀏覽:266
python隨機種子狀態釋放 瀏覽:11
51單片機做計數器 瀏覽:901
picc編譯器過期 瀏覽:735
在抖音收藏怎麼設置加密 瀏覽:394
外地雲伺服器如何注冊 瀏覽:860
遮瑕膏解壓 瀏覽:188
近的python少兒編程課 瀏覽:489
php當天時間戳 瀏覽:201
手機地圖app哪個好用 瀏覽:316
51單片機蓄電池三段式充電 瀏覽:281
rsa演算法java實現 瀏覽:38
java中讀取資料庫中數據 瀏覽:245
程序員買基金准則 瀏覽:257
伺服器連接到雲服務 瀏覽:297
程序員大笑的原因 瀏覽:79
騰訊雲伺服器充值費入什麼科目 瀏覽:764
如何解決我的世界國際版伺服器卡頓問題 瀏覽:425
27x25x40簡便計演算法 瀏覽:267