先创建db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/web08?useUnicode=true&characterEncoding=utf8 username=root password=root
注意不能有空格
package web09; /*获取连接和释放资源的方法 */ import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ResourceBundle; public class jdbc_text3 { private static String driver; private static String url; private static String username; private static String password; /* * 静态代码块获取配置文件信息 */ static{ ResourceBundle bundle = ResourceBundle.getBundle("db"); driver=bundle.getString("driver"); url=bundle.getString("url"); username=bundle.getString("username"); password=bundle.getString("password"); } public static Connection getconnection(){ Connection conn=null; //賦值是爲了防止空指針 try { Class.forName(driver); //注册驱动 conn = DriverManager.getConnection(url,username,password); //获取连接 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } public static void release(Connection conn,PreparedStatement pstmt ,ResultSet rs){ //获取连接,创建预处理对象,执行查询操作 if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(pstmt!=null){ try { pstmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
创建配置的工具类
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.junit.Before; import org.junit.Test; /** * 测试工具类 * * @author Administrator * */ public class jdbc_text2 { @Test public void testAdd() { Connection conn = null; PreparedStatement pstmt = null; try { // 1获取链接 conn = jdbc_text3.getconnection(); // 2编写sql语句 String sql = "insert into tbl_user values(null,?,?)"; // 3获取sql的语句对象 pstmt = conn.prepareStatement(sql); // 4设置参数 pstmt.setString(1, "lisi"); pstmt.setString(2, "hehe"); // 5执行插入炒作 int row = pstmt.executeUpdate(); if (row>0) { System.out.println("插入成功"); } else { System.out.println("插入失败"); } } catch (Exception e) { } finally { // 6释放资源 jdbc_text3.release(conn, pstmt, null); ; } } }
执行代码....但是,,,,,,不知道为啥...抛出runtimection 报错....我有时间问下别老大..
@test 报错...
抛extion 不跑错但是也运行不出来...
测试出来了...表里面有4个数据,,,我只是插入了3个