import java.sql.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.Date; import java.text.*; import java.util.Calendar; public class conn { public static void main(String[] args) { conn lm = new conn(); String t= lm.getStringDate(); try { Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序 } catch (Exception e) { e.printStackTrace(); } try { Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3307/student","root","zhangyabiao"); //连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码 System.out.println("["+t+"]"+"成功连接数据库! "); Statement stmt = connect.createStatement(); ResultSet rs = stmt.executeQuery("select * from zh"); //user 为你表的名称 while (rs.next()) { System.out.println(rs.getString("n")+". "+rs.getString("n1")+" "+rs.getString("n2")); } System.out.println("["+t+"]"+"成功获得数据"); } catch (Exception e) { System.out.print("["+t+"]"+"获得数据失败"); e.printStackTrace(); } } public static String getStringDate() { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = formatter.format(currentTime); return dateString; } }
结果测试
/* [2017-05-08 22:05:48]成功连接数据库! ...... [2017-05-08 22:05:48]成功获得数据 出现上面结果,说明你连接数据库成功。 */
时间: 2024-11-10 07:02:22