package cn.tedu.jdbc;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 6步实现JDBC
* @author 16
*
*/
public class Demo1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//1.注册数据库驱动
//在注册数据库驱动过程中,利用构造方法注册驱动,在Driver类中的static块中也会注册一次,我们手动又注册一次
//代码与我们导入的Driver类所在的包被绑死在了一起,如果修改数据库,需要回到代码当中,对导入的包进行修改。
// DriverManager.registerDriver(new Driver());
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接
// Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb2", "root", "root");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb2?user=root&password=root");
//jdbc:mysql:///mydb2
//jdbc:mysql://localhost:3306/mydb2?user=root&password=root
//3.创建一个传输器
Statement stat = conn.createStatement();
//4.利用传输器传输数据,并返回结果集。
ResultSet rs = stat.executeQuery("select * from user");
//5.遍历结果
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString(2);
Date date = rs.getDate("birthday");
System.out.println("id:"+id+"name:"+name+"date:"+date);
}
// rs.beforeFirst();//表示回到第一行之前的一行
// rs.previous();//表示向前一行
// rs.absolute(2);//表示移动到第二行
//6.关闭资源
//后创建的先关闭
rs.close();
stat.close();
conn.close();
}
}
package cn.tedu.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import cn.tedu.jdbc.utils.JDBCUtils;
public class Demo2 {
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
@Test
public void del() {
try{
conn = JDBCUtils.getConn();
stat = conn.createStatement();
int count = stat.executeUpdate("delete from user where id = 5");
if(count>0){
System.out.println("操作成功,受到影响的行数为:"+count);
}else{
System.out.println("操作失败");
}
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}finally{
JDBCUtils.close(rs, stat, conn);
}
}
/**
* 增加一条新的数据
*/
@Test
public void add() {
try{
conn = JDBCUtils.getConn();
stat = conn.createStatement();
//4.利用传输器传输数据,并返响应行数。
int count = stat.executeUpdate("insert into user values(null,'wangw','23233','wwwws@qq.com','2018-08-23')");
if(count > 0){
System.out.println("操作成功,受到影响的行数为:"+count);
}else{
System.out.println("操作失败");
}
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}finally{
//6.关闭资源
//后创建的先关闭
JDBCUtils.close(rs, stat, conn);
}
}
/**
* 更新一条数据
*/
@Test
public void update() {
try{
conn = JDBCUtils.getConn();
stat = conn.createStatement();
//4.利用传输器传输数据,并返响应行数。
int count = stat.executeUpdate("update user set name = 'ldss' where id = 4");
if(count > 0){
System.out.println("操作成功,受到影响的行数为:"+count);
}else{
System.out.println("操作失败");
}
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}finally{
//6.关闭资源
//后创建的先关闭
JDBCUtils.close(rs, stat, conn);
}
}
}
package cn.tedu.jdbc.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
private static Properties prop = null;
private JDBCUtils() {
}
static{
prop = new Properties();
try {
prop.load(new FileInputStream(JDBCUtils.class.getClassLoader().getResource("conf.properties").getPath()));
//p.load(new FileInputStream(new File(MyJDBCUtils.class.getClassLoader().getResource("conf.properties").getPath())));
//p.load(MyJDBCUtils.class.getResourceAsStream("/conf.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//创建连接static
/**
* 创建连接
* @return
* @throws ClassNotFoundException
* @throws SQLException
* @throws IOException
* @throws FileNotFoundException
*/
public static Connection getConn() throws ClassNotFoundException, SQLException, FileNotFoundException, IOException{
Class.forName(prop.getProperty("driver"));
return DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("user"),prop.getProperty("password"));
}
//关闭连接
/**
* 关闭连接
* @param rs
* @param stat
* @param conn
*/
public static void close(ResultSet rs,Statement stat,Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs = null;
}
}
if(stat != null){
try {
stat.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
stat = null;
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
conn = null;
}
}
}
}
package cn.tedu.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
import cn.tedu.jdbc.utils.JDBCUtils;
public class Login {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名:");
String name = sc.nextLine();
System.out.println("请输入密码:");
String password = sc.nextLine();
login(name,password);
}
/**
* 利用statement查询数据库信息实现登录功能
* @param name
* @param password
*/
public static void login(String name, String password){
Connection conn = null;
Statement stat = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConn();
stat = conn.createStatement();
rs = stat.executeQuery("select * from user where name = '"+name+"' and password='"+password+"'");
if(rs.next()){
System.out.println("登录成功!");
}else{
System.out.println("用户不存在!");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.close(rs, stat, conn);
}
}
}
/**
* PreparedStatement登录
*/
public static void PreLogin(String name, String password){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = JDBCUtils.getConn();
ps = conn.prepareStatement("select * from user where name = ? and password= ?");
ps.setString(1, name);
ps.setString(2,password);
rs = ps.executeQuery();
if(rs.next()){
System.out.println("pre登录成功");
}else{
System.out.println("pre登录失败");
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtils.close(rs, ps, conn);
}
}
package cn.tedu.pool;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import javax.sql.DataSource;
/**
* 手写连接池
* @author 16
*
*/
public class MyPool implements DataSource{
//定义一个能够存储连接的数据结构,由于经常使用插入和删除操作,所以List较好。
private static List<Connection> pool = new LinkedList<Connection>();
static{//在程序之后立刻创建一批连接以备使用
try{
Class.forName("com.mysql.jdbc.Driver");
for(int i=0;i<5;i++){
//每次都创建一个新的连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb2?user=root&password=root");
//将创建好的每一个连接对象添加到List中,模拟将连接加入连接池
pool.add(conn);
}
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
//创建连接(从连接池中取出一个连接)
@Override
public Connection getConnection() throws SQLException {
if(pool.size()==0){//取出连接之前首先判断当前连接池中是否还有连接,如果没有则重新创建一批连接
for(int i=0;i<5;i++){
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb2?user=root&password=root");
pool.add(conn);
}
}
//从List中取出一个连接对象
//此处不能使用get(),get()方法只能读取对应下标的元素,没有将读取到的元素移除,如果是取出连接对象,应将对象移除。
Connection conn = pool.remove(0);
ConnDecorate connpool = new ConnDecorate(conn,this);
System.out.println("成功获取一个连接,池中还剩:"+pool.size()+"个连接");
return connpool;
}
//返还连接
//手写一个返还连接的方法
public void retConn(Connection conn){
try {
//归还的连接如果已经关闭或者为空,则不允许放入池中。
if(conn!=null&&!conn.isClosed()){
pool.add(conn);
System.out.println("成功还回一个连接,池中还剩:"+pool.size()+"个连接");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class ConnDecorate implements Connection{
public Connection conn = null;
public MyPool pool = null;
public ConnDecorate(Connection conn,MyPool pool){
this.conn = conn;
this.pool = pool;
}
@Override
public void close() throws SQLException {
pool.returnConnection(conn);
}
public <T> T unwrap(Class<T> iface) throws SQLException {
return conn.unwrap(iface);
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return conn.isWrapperFor(iface);
}
public Statement createStatement() throws SQLException {
return conn.createStatement();
}
public PreparedStatement prepareStatement(String sql) throws SQLException {
return conn.prepareStatement(sql);
}
public CallableStatement prepareCall(String sql) throws SQLException {
return conn.prepareCall(sql);
}
public String nativeSQL(String sql) throws SQLException {
return conn.nativeSQL(sql);
}
public void setAutoCommit(boolean autoCommit) throws SQLException {
conn.setAutoCommit(autoCommit);
}
public boolean getAutoCommit() throws SQLException {
return conn.getAutoCommit();
}
public void commit() throws SQLException {
conn.commit();
}
public void rollback() throws SQLException {
conn.rollback();
}
public boolean isClosed() throws SQLException {
return conn.isClosed();
}
public DatabaseMetaData getMetaData() throws SQLException {
return conn.getMetaData();
}
public void setReadOnly(boolean readOnly) throws SQLException {
conn.setReadOnly(readOnly);
}
public boolean isReadOnly() throws SQLException {
return conn.isReadOnly();
}
public void setCatalog(String catalog) throws SQLException {
conn.setCatalog(catalog);
}
public String getCatalog() throws SQLException {
return conn.getCatalog();
}
public void setTransactionIsolation(int level) throws SQLException {
conn.setTransactionIsolation(level);
}
public int getTransactionIsolation() throws SQLException {
return conn.getTransactionIsolation();
}
public SQLWarning getWarnings() throws SQLException {
return conn.getWarnings();
}
public void clearWarnings() throws SQLException {
conn.clearWarnings();
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
return conn.createStatement(resultSetType, resultSetConcurrency);
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
return conn.prepareStatement(sql, resultSetType, resultSetConcurrency);
}
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
return conn.prepareCall(sql, resultSetType, resultSetConcurrency);
}
public Map<String, Class<?>> getTypeMap() throws SQLException {
return conn.getTypeMap();
}
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
conn.setTypeMap(map);
}
public void setHoldability(int holdability) throws SQLException {
conn.setHoldability(holdability);
}
public int getHoldability() throws SQLException {
return conn.getHoldability();
}
public Savepoint setSavepoint() throws SQLException {
return conn.setSavepoint();
}
public Savepoint setSavepoint(String name) throws SQLException {
return conn.setSavepoint(name);
}
public void rollback(Savepoint savepoint) throws SQLException {
conn.rollback(savepoint);
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
conn.releaseSavepoint(savepoint);
}
public Statement createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
return conn.createStatement(resultSetType, resultSetConcurrency,
resultSetHoldability);
}
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
return conn.prepareStatement(sql, resultSetType, resultSetConcurrency,
resultSetHoldability);
}
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
return conn.prepareCall(sql, resultSetType, resultSetConcurrency,
resultSetHoldability);
}
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException {
return conn.prepareStatement(sql, autoGeneratedKeys);
}
public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
throws SQLException {
return conn.prepareStatement(sql, columnIndexes);
}
public PreparedStatement prepareStatement(String sql, String[] columnNames)
throws SQLException {
return conn.prepareStatement(sql, columnNames);
}
public Clob createClob() throws SQLException {
return conn.createClob();
}
public Blob createBlob() throws SQLException {
return conn.createBlob();
}
public NClob createNClob() throws SQLException {
return conn.createNClob();
}
public SQLXML createSQLXML() throws SQLException {
return conn.createSQLXML();
}
public boolean isValid(int timeout) throws SQLException {
return conn.isValid(timeout);
}
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
conn.setClientInfo(name, value);
}
public void setClientInfo(Properties properties)
throws SQLClientInfoException {
conn.setClientInfo(properties);
}
public String getClientInfo(String name) throws SQLException {
return conn.getClientInfo(name);
}
public Properties getClientInfo() throws SQLException {
return conn.getClientInfo();
}
public Array createArrayOf(String typeName, Object[] elements)
throws SQLException {
return conn.createArrayOf(typeName, elements);
}
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
return conn.createStruct(typeName, attributes);
}
}