package cn.hncu;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.UUID;
import org.junit.Test;
import cn.hncu.pubs.ConnFactory;
public class JdbcDemo {
//查
@Test
public void readDemo() throws Exception{
Class.forName("com.mysql.jdbc.Driver");//驱动 ---jdbc4.0开始,这一句可以省略。
//hibernate框架,上一句不要省。
String url = "jdbc:mysql://127.0.0.1:3306/hncu?useUnicode=true&characterEncoding=utf-8";//hncu这个是你要使用账号登陆数据库3306是你数据库的接
口;
Connection con = DriverManager.getConnection(url,"root","1234");
//System.out.println(con);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from person2"); //该方法专用于查询
while(rs.next()){
String id0 = rs.getString(1);
Object id = rs.getObject(1);//字段序号
Object nm = rs.getObject("name"); //字段名
String ch = rs.getString(3);
if(ch.trim().equals("0")){
ch="女";
}else if(ch.trim().equals("1")){
ch="男";
}else{
ch="未知";
}
System.out.println(id0+"-"+id+","+nm+","+ch);
}
con.close();
}
//增
@Test
public void saveDemo() throws Exception{
Connection con = ConnFactory.getConn();
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
//增
//String uuid = UUID.randomUUID().toString().replace("-", "");
//String sql = "INSERT INTO person2 VALUES('"+uuid+"','"+name+"','1')";
//INSERT INTO person2 VALUES('P09','赵子龙','1');
//改
//String sql = "UPDATE person2 SET NAME = CONCAT(NAME,'"+name+"') WHERE LENGTH(id)<4";
//UPDATE person2 SET NAME = CONCAT(NAME,"x") WHERE LENGTH(id)<4;
//删
String sex="0";
String sql = "delete from person2 where sex='"+sex+"'";
//delete from person2 where sex='0';
System.out.println("sql: "+ sql);
Statement st = con.createStatement();
int a = st.executeUpdate(sql); //该方法一般用于如下操作:增insert、删delete、改update
//上面方法的返回值: 影响的行数
System.out.println("影响的行数:"+a);
con.close();
}
}