public class JDBCTest { public static void main(String[] args){ String driver = "com.mysql.jdbc.Driver"; String url= "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "123456"; try{ // 加载驱动程序 Class.forName(driver); // 连续数据库 Connection conn = (Connection) DriverManager.getConnection(url, user, password); if(!conn.isClosed()) System.out.println("Succeeded connecting to the Database!"); // statement用来执行SQL语句 Statement statement = (Statement) conn.createStatement(); // 要执行的SQL语句 String sql = "select * from employee"; // 结果集 ResultSet rs = (ResultSet) statement.executeQuery(sql); System.out.println("-----------------"); System.out.println("姓名" +" "+ "邮箱" +" "+ "日期"); System.out.println("-----------------"); while(rs.next()) { // 从mysql中获取数据 String uname = rs.getString("name"); String uemail = rs.getString("email"); String uhiredate = rs.getString("hiredate"); // 首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。 // 然后使用GB2312字符集解码指定的字节数组 //name = new String(name.getBytes("gb2312"),"gb2312"); // 输出结果 System.out.println(uname +" "+ uemail +" "+ uhiredate); } rs.close(); conn.close(); }catch(ClassNotFoundException e) { System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); }catch(SQLException e) { e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } } }
结果如下:
使用dos查看数据库结果如下: