Java访问Mysql数据库的实例

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

你可能感兴趣的:(Java,Mysql)