注:动态的接收用户命令,应保证Connection重用。
方法:用Scanner类动态接受命令,开发一个main函数或构造或测试死循环;
相同代码抽取出来放到另外一个类里,开发一个类维护一个唯一的Connection;
这个类就叫做工厂方法,工厂模式生产别人的。
1:工厂模式类:
package cn.JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnUtils {
private static Connection con;
static{
try {
Class.forName("oracle.jdbc.OracleDriver");
String url="jdbc:oracle:thin:@192.168.0.64:1521/xe";
con=DriverManager.getConnection(url,"lxl","1234");
} catch (Exception e) { //异常转换
throw new RuntimeException(e);
}
}
public static Connection getConn(){
return con;
}
}
2:main
package cn.JDBC;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
import java.util.UUID;
import org.junit.Test;
public class Demo01 {
@Test
public void query() throws Exception{
Connection con=ConnUtils.getConn();
Statement st=con.createStatement();
//结果集
ResultSet rs=st.executeQuery("select * from stud");
//遍历,输出各项
while(rs.next()){
String id=rs.getString("id");
String name =rs.getString("name");
int age=rs.getInt("age");
String sex=rs.getString("sex");
System.err.println(id+","+name+","+age+","+sex);
}
rs.close();
st.close();
}
Scanner sc=new Scanner(System.in);
//插入数据
@Test
public void insert() throws Exception{
Connection con=ConnUtils.getConn();
Statement st=con.createStatement();
System.err.println("plz enter name:");
String name =sc.nextLine();
System.err.println("plz enter age");
String age=sc.nextLine();
System.err.println("plz enter sex");
String sex=sc.nextLine();
String id=UUID.randomUUID().toString().replace("-","");
String sql="insert into stud(id,name,age,sex) values('"+id+"','"+name+"','"+age+"','"+sex+"')";
int i=st.executeUpdate(sql);
System.err.println("影响的行数"+i);
st.close();
}
//删除数据
@Test
public void delete() throws Exception{
Connection con=ConnUtils.getConn();
Statement st=con.createStatement();
System.err.println("plz enter id for delete:");
String id=sc.nextLine();
String sql="delete from stud where id='"+id+"'";
int i=st.executeUpdate(sql);
System.err.println("删除的行数:"+i);
st.close();
}
//修改数据
@Test
public void update() throws Exception{
Connection con=ConnUtils.getConn();
Statement st=con.createStatement();
System.err.println("plz enter id for update:");
String id=sc.nextLine();
System.err.println("plz enter new name to be:");
String name=sc.nextLine();
String sql="update stud set name='"+name+"' where id='"+id+"'";
int i=st.executeUpdate(sql);
System.err.println("修改的行数:"+i);
st.close();
}
@Test
public void main() throws Exception{
one:while(true){
System.err.println("1:query\n2:insert\n3:delete\n4:update\n0:exit");
String op=sc.nextLine();
switch(op){
case "1":
query();
break;
case "2":
insert();
break;
case "3":
delete();
break;
case "4":
update();
break;
case "0":
ConnUtils.getConn().close();
break one;
default:
break;
}
}
}
}