要牢记的步骤,编个口诀记来玩,记熟了就慢慢理解了。这个星期边学语法边巩固jdbc。
记住口诀:包参驱动连接
- 加载mysql驱动包。
- 定义各种连接所需参数。
- 加载驱动程序(class.forname是反射机制),class.forName(driver)。
- 获取连接(需要drivermanager.getconnection),Connection conn = DriverManager.getConnection(DBURL,USER,PASS)。
一、代码实现
下面是用口诀写出来的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package jdbc; import java.sql.DriverManager; //包 import java.sql.SQLException; import com.mysql.jdbc.Connection; public class dbconnection { private static final String driver = "com.mysql.jdbc.Driver"; //参 private static final String url = "jdbc:mysql://127.0.0.1:3306/testmysql"; private static final String user = "root"; private static final String pass = "root"; public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName(driver); //驱动 Connection conn = null; try { conn = (Connection) DriverManager.getConnection(url, user, pass);//链接 } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } try{ System.out.println(conn); System.out.println("connection succeed"); }catch(Exception e) { e.printStackTrace(); System.out.println("connection fail"); } } } |
还可以加强,可以把连接写成static程序块,每次执行程序时默认加载,很方便。然后写个getConn的方法,以后连接就可以直接调用了,不用再赋值。
加强一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package jdbc; import java.sql.DriverManager; //包 import java.sql.SQLException; import com.mysql.jdbc.Connection; public class dbconnection { private static final String driver = "com.mysql.jdbc.Driver"; //参 private static final String url = "jdbc:mysql://127.0.0.1:3306/testmysql"; private static final String user = "root"; private static final String pass = "root"; public static Connection conn = null; static{ try { Class.forName(driver); //驱动 conn = (Connection) DriverManager.getConnection(url, user, pass);//链接 } catch (Exception e) { e.printStackTrace(); // TODO: handle exception } try{ System.out.println(conn); System.out.println("connection succeed"); }catch(Exception e) { e.printStackTrace(); System.out.println("connection fail"); } } public static Connection getConnection() { return conn; } public static void main(String[] args) throws ClassNotFoundException, SQLException { } } |
需要连接直接调用Connection conn = 类名.getConnection()。
二、总结
记录一下。