连接mysql数据库操作
加载mysql驱动,下一个驱动的jar包;
Connection con;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "123456";
try{
Class.forName(driver);
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed()){
System.out.println("Succeeded connecting to the Database!");
}
Statement statement = con.createStatement();
String sql = "select * from users";
ResultSet rs = statement.executeQuery(sql);
System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------");
System.out.println("用户名" + "\t" + "密码");
System.out.println("-----------------");
String username = null;
String pass_word = null;
while(rs.next()){
username = rs.getString("USER_NAME");
pass_word = rs.getString("PASSWORD");
System.out.println(username + "\t" + pass_word);
}
rs.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
finally{
System.out.println("数据库数据成功获取!!");
}