JDBC链接数据库的方式
方式1:直接按步骤写,不推荐
public class Threejdbctset { public static void main(String [] agrs){ Connection con=null; Statement sta=null; try { //注册驱动 Driver dri=new com.mysql.cj.jdbc.Driver(); DriverManager.registerDriver(dri); String url="jdbc:mysql://localhost:3306/mydate";//本机库名字 String user="root";//用户 String password="123456";//密码 con=DriverManager.getConnection(url,user,password);//链接 System.out.println("数据库链接成功"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(sta!=null) { try { sta.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }if(con!=null) { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
第二种:反射机制
(注意第一种和第二种的区别在于 Class.forName("com.mysql.cj.jdbc.Driver")在类加载的时候执行了这个包的static 静态代码块,其中的类容就是第一种所写的)
static { Driver driver=new com.mysql.cj.jdbc.Driver(); DriverManager.registerDriver(driver); }
public class Threejdbctset { public static void main(String [] agrs){ Connection con=null; Statement sta=null; try { //注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/mydate";//本机库名字 String user="root";//用户 String password="123456";//密码 con=DriverManager.getConnection(url,user,password);//链接 System.out.println("数据库链接成功"); } catch (SQLException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(sta!=null) { try { sta.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }if(con!=null) { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
第三种:小编比较推荐,也是常用的一种(配置文件)
首先是配置文件,名字格式是XXXX.properties
然后是代码块
public class Threejdbctset { public static void main(String [] agrs){ //资源绑定器 ResourceBundle ban=ResourceBundle.getBundle("链接数据库/jdbc"); String dri=ban.getString("driver"); String url=ban.getString("url"); String user=ban.getString("user"); String password=ban.getString("password"); Connection con=null; Statement sta=null; try { //注册驱动 Class.forName(dri); con=DriverManager.getConnection(url,user,password);//链接 System.out.println("数据库链接成功"); } catch (SQLException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(sta!=null) { try { sta.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }if(con!=null) { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
第三种虽然看着比较麻烦,但是它没有将数据库写死在程序之中,对于不同的用户只需要更改对应的配置文件就可以了
下一篇:
如何从Mysql快速查找一条数据