JAVA連線mysql資料庫例程
阿新 • • 發佈:2019-02-07
package com.xmty.testmysql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Test { public int getPushTime() { int time = 0; String dbDriver = "com.mysql.jdbc.Driver"; String dbUrl = "jdbc:mysql://localhost:3306/timetask?user=root&password=tiger"; String dbUser = "root"; String dbPassword = "tiger"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { Class.forName(dbDriver); conn = DriverManager.getConnection(dbUrl); String sql = "select * from timeint"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); if (rs.next()) { time = rs.getInt("time"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (null != conn) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } conn = null; } if (null != stmt) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } stmt = null; } if (null != rs) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } rs = null; } } System.out.println("獲取的時間為:" + time); return time; } public static void main(String[] args) { new Test().getPushTime(); } }