本文主要是介绍JDBC学习一 基础 一个简单的增删该查例子,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
jdbcUtil02.java
//单例模式
public final class jdbcUtil02 {
static String url = "jdbc:mysql://localhost:3306/jdbc";
static String username = "root";
static String password = "root";
//private static jdbcUtil02 instance = new jdbcUtil02();
private static jdbcUtil02 instance= null;
//构造私有化
private jdbcUtil02(){
}
//提供一个公共的static方法
public static jdbcUtil02 getInstance(){
if (instance==null) {
//延迟加载 使用的时候new
//处理并发问题 可以加锁
synchronized (jdbcUtil02.class) {
instance = new jdbcUtil02();
}
}
return instance;
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
public static void free(Statement st, Connection conn, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
}
}
}
package com.sg.test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
public class JdbcCRUDTest {
// 查询
@Test
public void select() throws Exception {
Connection conn = jdbcUtil02.getInstance().getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from user");
while (rs.next()) {
System.out.println("id:" + rs.getInt("id") + "\n name:"
+ rs.getString("name") + "\n age:" + rs.getInt("age")
+ "\n sex" + rs.getString("sex") + "\n brithday:"
+ rs.getDate("brithday"));
}
// 关闭资源
jdbcUtil02.free(st, conn, rs);
}
//添加
@Test
public void insert() throws Exception {
Connection conn = jdbcUtil02.getInstance().getConnection();
Statement st = conn.createStatement();
String sql = "insert into user values(4,'name1',20,'nan','1992-12-28')";
int i = st.executeUpdate(sql);
System.out.println("i = "+i);
}
//修改
@Test
public void update() throws Exception {
Connection conn = jdbcUtil02.getInstance().getConnection();
Statement st = conn.createStatement();
String sql = "update user set age = 30 where id = 1";
int i = st.executeUpdate(sql);
}
//删除
@Test
public void delete() throws Exception {
Connection conn = jdbcUtil02.getInstance().getConnection();
Statement st = conn.createStatement();
String sql = "delete from user where id > 2";
int i = st.executeUpdate(sql);
}
}
这篇关于JDBC学习一 基础 一个简单的增删该查例子的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!