public class DBUtil {
static {
try {
// Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//增加
public void insert(){
Connection conn = getConnection();
PreparedStatement ps = null;
try {
setAutoCommit(conn, false);
String sql = " insert into tb_test (name) values (?) ";
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.execute();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
rollback(conn);
}finally{
close(ps);
close(conn);
}
}
public void findOne(){
/*ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);*/
int list[] = {1, 2};
Connection conn = getConnection();
PreparedStatement ps = null;
try {
String sql = " select id, name from tb_test where id in (?) ";
ps = conn.prepareStatement(sql);
ps.setObject(1, list);
ResultSet rs = ps.executeQuery();
/*if(rs.next()){
String result = rs.getString("id") + ":" + rs.getString("name");;
System.out.println(result);
}*/
while(rs.next()){
String result = rs.getString(1) + ":" + rs.getString(2);;
System.out.println(result);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
close(ps);
close(conn);
}
}
public void find(){
Connection conn = getConnection();
PreparedStatement ps = null;
try {
String sql = " select id, name from tb_test ";
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
String result = rs.getString(1) + ":" + rs.getString(1);;
System.out.println(result);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
close(ps);
close(conn);
}
}
//获取数据库连接
public static Connection getConnection() {
// String url = "jdbc:oracle:thin:@localhost:1521:testdb";
try {
String url = "jdbc:mysql://localhost:3306/dome";
String user = "root";
String password = "123456";
return DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void setAutoCommit(Connection connection, boolean auto) {
try {
connection.setAutoCommit(auto);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void rollback(Connection connection) {
try {
connection.rollback();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(PreparedStatement ps) {
try {
if (null != ps) {
ps.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs) {
try {
if (null != rs) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(PreparedStatement ps, ResultSet rs) {
try {
close(ps);
close(rs);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
DBUtil db = new DBUtil();
/*db.insert();
db.find(); */
db.findOne();
}
}
JDBC基础操作DOME
最新推荐文章于 2023-11-28 17:25:38 发布