import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 创建数据库连接
* 懒汉式:单例模式
* @author Administrator
*
*/
public class CreatConnection {
public static CreatConnection cconn=null;
public static Connection conn =null;
private CreatConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useSSL=false", "root", "123456");
} catch (ClassNotFoundException | SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public static CreatConnection getInstance(){
if(cconn == null){
synchronized(CreatConnection.class) {
if(cconn == null){
cconn = new CreatConnection();
}
}
}
return cconn;
}
}
package com.jdbc.test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* JDBC简单使用Demo
* @author Administrator
*
*/
public class TestJDBC {
public static void main(String[] args) {
// TODO 自动生成的方法存根
CreatConnection cc = CreatConnection.getInstance();
Connection conn = cc.conn;//获取数据库连接,这里使用了单例模式建立连接
String sql = "insert into student (id,name,sex,age) value('61','小兰','女','18')";
ResultSet rs =null;//创建结果集对象
try {
//获取Statement对象,用于向数据库发送SQL语句
Statement statement = conn.createStatement();
statement.executeUpdate(sql);//执行SQL语句,该方法主要用于删除,更新,增加操作,返回受影响的条数
for(int i=1;i<11;i++){
String str = "insert into student (id,name,sex,age) value('"+i+"','小兰','女','18')";
statement.addBatch(str);//批量获取SQL语句
}
statement.executeBatch();//批量处理SQL语句
System.out.println(statement.executeUpdate("delete from student where id ='61'"));
//获取查询结果
rs = statement.executeQuery("select * from student");
//结果集迭代
while(rs.next()){
String id = rs.getString(1);
String name = rs.getString(2);
String sex = rs.getString(3);
int age = rs.getInt(4);
System.out.println("记录值:id:"+id+" name:"+name+" :sex"+sex+" age:"+age);
}
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
finally{
try {
//关闭连接
conn.close();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}