java jdbc 连接方式
记录下jdbc连接方式
1.mysql
View Code
1 public Connection getConn() throws SQLException { 2 MysqlDataSource ds = new MysqlDataSource(); 3 ds.setUrl("jdbc:mysql://localhost:3306/test?user=root&password=1"); 4 return (Connection) ds.getConnection(); 5 6 }
2.通用 不同数据库用不同url(代码少个人比较喜欢)
View Code
public Connection getConn() throws SQLException { Driver d = new Driver(); return (Connection) d.connect("jdbc:mysql://localhost:3306/test?user=root&password=1", null); }
3.通用(最早接触的写法)
View Code
1 private static final String DEIVER = "com.mysql.jdbc.Driver"; 2 private static final String URL = "jdbc:mysql://localhost:3306/?"; 3 private static final String USER = "root"; 4 private static final String PWd = "1"; 5 6 //加载驱动 7 static { 8 try { 9 Class.forName(DEIVER); 10 } catch (ClassNotFoundException e) { 11 e.printStackTrace(); 12 } 13 } 14 15 /** 16 *获取链接 17 * @return 链接对象 18 */ 19 20 public static Connection getConn() { 21 Connection conn = null; 22 try { 23 conn = (Connection) DriverManager.getConnection(URL, USER, PWd); 24 } catch (SQLException e) { 25 e.printStackTrace(); 26 } 27 return conn; 28 }


浙公网安备 33010602011771号