【JDBC】JDBC连接创建表和异常处理操作
1.使用JDBC的准备环境:
1):拷贝MySQL的JDBC驱动,到Java项目中:mysql-connector-java-5.1.26-bin.jar
注意:是jar包
2):选择jar,[buil path],把jar添加到classpath路径.
2.JDBC的操作步骤:
操作步骤: 1):加载注册驱动. Class.forName("com.mysql.jdbc.Driver"); 为什么说上述代码,在完成加载注册驱动? 上述代码: 1):把com.mysql.jdbc.Driver这一份字节码加载进JVM. 2):当一份字节码被加载进JVM,就会执行其静态代码块. 而其底层的静态代码块在完成注册驱动工作. 2):获取连接对象. 通过DriverManager的getConnection方法创建Connection对象. Connection conn = DriverManager.getConnection(url,username,password); url=jdbc:mysql://localhost:3306/jdbcdemo 如果连接的是本机的MySQL,并且端口是默认的3306,则可以简写: url=jdbc:mysql:///jdbcdemo username=root password=admin 可以通过 show processlist命令来查看有几个MySQL进程. 3):创建/获取语句对象. 4):执行SQL语句. 5):释放资源.
比如 执行插入语句:
@Test public void test() throws Exception { String sql = "create table student (id BIGINT(20) PRIMARY KEY , name varchar(20), age int(11))"; Connection connection = null; Statement statement = null; try { // 加载驱动 Class.forName("com.mysql.jdbc.Driver"); // 获取连接 connection = DriverManager.getConnection("jdbc:mysql:///jdbcdemo", "root", "root"); // 执行sql语句 statement = connection.createStatement(); statement.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e2) { e2.printStackTrace(); } finally { try { if (connection != null) { connection.close(); } } catch (Exception e3) { e3.printStackTrace(); } } } }
使用java7 的自动关闭资源
// 使用java7 的自动关闭资源 public void testjava7() { String sql = "create table student (id BIGINT(20) PRIMARY KEY , name varchar(20), age int(11))"; try (// 获取连接 Connection connection = DriverManager.getConnection("jdbc:mysql:///jdbcdemo", "root", "root"); // 执行sql语句 Statement statement = connection.createStatement();) { statement.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } }
执行查询语句:
// 查询语句 @Test public void selectedTest() throws Exception { String sql = "select * from product"; Connection connection = DriverManager.getConnection("jdbc:mysql:///jdbcdemo", "root", "root"); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getNString("productName"); System.out.println(id + name); } rs.close(); statement.close(); connection.close(); }
如果错过了一天,那么真的就错过一天。不抛弃,不放弃。点一盏心灯给自己。
浙公网安备 33010602011771号