Java訪問Mysql資料庫的例項
阿新 • • 發佈:2019-02-10
import java.sql.*; public class Mysql { public static void main(String arg[]) { try { Connection con = null; //定義一個MYSQL連結物件 Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL驅動 con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/menagerie", "root", ""); //連結本地MYSQL System.out.println("mysql connection success!"); Statement stmt; stmt = con.createStatement(); String selectSql = "select * from pet"; ResultSet selectRes = stmt.executeQuery(selectSql); while(selectRes.next()) { String name = selectRes.getString("name"); String owner = selectRes.getString("owner"); String birth = selectRes.getString("birth"); System.out.println("name:" + name + " owner:" + owner + " birth:" + birth); } } catch (Exception e) { System.out.print("MYSQL ERROR:" + e.getMessage()); } } }
輸出結果:
mysql connection success!
name:Fluffy owner:Harold birth:1993-02-04
name:Claws owner:Gwen birth:1994-03-17
name:Buffy owner:Harold birth:1989-05-13
name:Fang owner:Benny birth:1990-08-27
name:Bowser owner:Diane birth:1979-08-31
name:Chirpy owner:Gwen birth:1998-09-11
name:Whistler owner:Gwen birth:1997-12-09
name:Slim owner:Benny birth:1996-04-29
name:Puffball owner:Diane birth:2000-09-09