※※存储过程※※※
定义:
create procedure 过程名(参数)
begin
多条sql语句
end
调用:
call 过程名(实参)
实例1--无参的存储过程:
△小细节:要把默认的语句结束“;”号改成其它如“$$”,这样存储过程中定义的分号就不被看成是语句结束(否则会直接被提交)。最后再把“;”号还原成默认的结束符。
delimiter $$
create procedure p1()
begin
insert into stud values('P0010','小李',23);
select * from stud;
end$$
delimiter ;
call p1();
实例2--有参的存储过程:
delimiter $$
create procedure p2( in id varchar(32), in nm varchar(30), in age int )
begin
insert into stud values(id,nm,age);
select * from stud;
end$$
delimiter ;
call p2('P011','小五',28);
实例3--有返回值的存储过程:
delimiter $$
create procedure p3( in id varchar(32), in nm varchar(30), in age int, out num int )
begin
insert into stud values(id,nm,age);
select * from stud;
select count(*) into num from stud;
end$$
delimiter ;
CALL p3('P012','小小五',27, @aa); /*调用且用aa接收结果*/
SELECT @aa; /*显示用户变量aa*/
系统变量名称:@@变量名
用户变量名称:@变量名
//////////binary////////////////
mysql查询默认是不区分大小写的如:
select * from? table_name where? a like? 'a%'???
select * from? table_name where? a like? 'A%'???
select * from table_name where a like 'a%'
select * from table_name where a like 'A%'
效果是一样的。
要让mysql查询区分大小写,可以:
select? * from? table_name where? binary? a like? 'a%'??
select? * from? table_name where? binary? a like? 'A%'???
select * from table_name where binary a like 'a%'
select * from table_name where binary a like 'A%'
也可以在建表时,加以标识?
create table table_name(
a varchar(20) binary
)
/////事务处理////
DELETE FROM stud WHERE id='P006';
START TRANSACTION;
DELETE FROM stud WHERE id='P011';
UPDATE stud SET NAME='abc' WHERE id='P003';
ROLLBACK / COMMIT;
说明:从"START TRANSACTION"开始 到 “ROLLBACK; 或 COMMIT; ”,这中间的那么语句是一个整体,如果执行 “ROLLBACK”,那么这些动作都会回滚(撤消)。如果执行“COMMIT”,就全部执行成功。
////Java实现事务处理的简单模板////
// /////////以下演示Java中如何实现事务////////////
// /////////以下演示Java中如何实现事务////////////
try {
con.setAutoCommit(false);// 对应mysql中的“START TRANSACTION;”的功能
String sql = "INSERT INTO sstud VALUES('1017','杨过',30,'武侠','1')";
st.execute(sql);// 增
sql = "delete from sstud where sno='1015' ";
st.execute(sql);// 删
//sql = "update sstud set saddresos='中国北京' where sname='刘备' ";// 注意,这种方式不能写多条sql语句(中间用分号隔也不行)
sql = "update sstud set saddress='中国北京' where sname='刘备' ";// 注意,这种方式不能写多条sql语句(中间用分号隔也不行)
st.execute(sql);// 改
con.commit();
System.out.println("事务提交了.....");
} catch (Exception e) {
System.out.println("事务回滚了.....");
con.rollback();
}
查询事务隔离级别:
select @@tx_isolation;
设置事务隔离级别(read-uncommitted):set session transaction isolation level read uncommitted;//可以读到没有其他客户端提交的
设置事务隔离级别(read-committed):set session transaction isolation level read committed;//可以读到其他客户端提交的信息
设置事务隔离级别(repeatable-read,默认):set session transaction isolation level repeatable read;//其他客户端操作对自己不会有影响
设置事务隔离级别(serializable,最高级别):set session transaction isolation level serializable;//相当于单线程操作,在进行查询时就会对表或行加上共享锁,其他事务对该表将只能进行读操作,而不能进行写操作
package cn.hncu.demo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import org.junit.Test;
import cn.hncu.utils.ConnectFactory;
public class JdbcDemo {
Connection con=ConnectFactory.getCon();
/*Statement中有4个执行方法可用
* 1, executeQuery() : 只能执行查询语句
* 2, executeUpdate(): 只能增、删、改, 不能执行查询语句
* 3, execute(): 增、删、改、查的语句都能够执行。只是查询时返回的结果是告诉成功与否,如果要获取查询结果,得另外用" st.getResultSet()"获取
* 4, executeBatch()//批处理,可以处理多条语句
*/
@Test
public void results() throws SQLException{
Statement st=con.createStatement();
String sql="select * from book";
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
Integer id=rs.getInt(1);
String name=rs.getString("name");
Double price=rs.getDouble(3);
String birth=rs.getDate(4)+" "+rs.getTime(4);//注意获取日期时间型数据的方式
System.out.println(id+","+name+","+price+","+birth);
}
con.close();
}
@Test
public void execute() throws SQLException{
Statement st=con.createStatement();
String sql=null;
// sql="INSERT INTO book(NAME,price,birth) VALUES('oracle',50.11,'2015-8-8 19:33:10')";
// sql="DELETE FROM book WHERE name='oracle';";
sql="update book set price=price*1.8 where name='sql'";
st.execute(sql);
results();
}
@Test
public void executeUpdate() throws Exception{
Statement st=con.createStatement();
String sql=null;
// sql="INSERT INTO book(NAME,price,birth) VALUES('oracle',50.11,'2015-8-8 19:33:10')";
sql="DELETE FROM book WHERE name='oracle';";
//sql="update book set price=price*1.8 where name='sql'";
int num=st.executeUpdate(sql);//返回值是影响的行数
System.out.println(num);
results();
}
@Test //容易产生bug:如输入name值为: b'c
public void reg() throws Exception{
Statement st=con.createStatement();
Scanner sc=new Scanner(System.in);
String id=sc.nextLine();
String name =sc.nextLine();
Integer age=Integer.parseInt(sc.nextLine());
String sql="INSERT INTO stud(id,name,age) values('"+id+"','"+name+"',"+age+")";
boolean boo=st.execute(sql);//不能用boolean来判断,因为返回时ResultSet才是YES
// if(boo){
// System.out.println("注册成功");
// }else {
// System.out.println("注册失败");
// }
}
@Test //容易产生bug:如输入name值为: 'a' or '1=1
public void login() throws Exception{
Statement st=con.createStatement();
Scanner sc=new Scanner(System.in);
String id=sc.nextLine();
String name =sc.nextLine();
String sql=null;
sql="select count(*) from stud where id='"+id+"' and name='"+name+"'";
ResultSet rs=st.executeQuery(sql);
rs.next();
int n = rs.getInt(1);
System.out.println(sql);
if(n<=0){
System.out.println("登录失败");
}else {
System.out.println("登录成功");
}
con.close();
}
//采用PrepareStatement
@Test //不会被黑:如输入name值为: a' or '1'='1
public void login2() throws Exception{
Statement st=con.createStatement();
Scanner sc=new Scanner(System.in);
String id=sc.nextLine();
String name =sc.nextLine();
String sql=null;
sql="select count(*) from stud where id=? and name=?";
//创建预处理语句对象
PreparedStatement ps=con.prepareStatement(sql);
//给占位设置值---设置参数
//给第1个参数设置
ps.setString(1, id);
//给第2个参数设置
ps.setString(2, name);
ResultSet rs =ps.executeQuery();//不接受参数
rs.next();
int n = rs.getInt(1);
if(n<=0){
System.out.println("登录失败...");
}else{
System.out.println("登录成功....");
}
con.close();
}
@Test//获取自动增长列的值
public void getAuto() throws SQLException{
Statement st=con.createStatement();
String sql="INSERT INTO book(NAME,price,birth) VALUES('红楼梦',100.11,'2015-5-8 19:23:10');";
st.execute(sql, Statement.RETURN_GENERATED_KEYS);//需要调用Statement.RETURN_GENERATED_KEYS
ResultSet rs=st.getGeneratedKeys();
while(rs.next()){
int id=rs.getInt(1);
System.out.println("自动增长的值"+id);
}
}
@Test//获取自动增长列的值PrepareStatement
public void getAuto2() throws SQLException{
String sql="INSERT INTO book(NAME,price,birth) VALUES(?,?,'2015-5-8 19:23:10');";
PreparedStatement ps=con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "西游记");
// ps.setInt(2, 59);//能插入,但是会报错!
ps.setDouble(2, 60.9);
ps.execute();
ResultSet rs=ps.getGeneratedKeys();
while(rs.next()){
int id=rs.getInt(1);
System.out.println("自动增长的值"+id);
}
}
@Test
/*执行批处理---自己本身不带事务,如果其中某条sql挂,则后续的sql执行失败,
前面的还是有效的。如果要事务,另外再采用:con.setAutoCommit(false)+
try-cacth+ rollback/commit*/
public void batchDemo() throws SQLException{
Statement st=con.createStatement();
String sql="INSERT INTO book(NAME,price,birth) VALUES('aa',2,'2016-5-8 19:23:10')";//有没有分号都一样
for(int i=0;i<5;i++){
// if(i==3){
// sql="INSERT INTO book(NAME,price,birth) VALUES('aa,2,'2016-5-8 19:23:10')";//有没有分号都一样
// }
st.addBatch(sql);
}
int[] nums=st.executeBatch();
for(int i=0;i@Test
public void prepBatchDemo() throws SQLException{
String sql="INSERT INTO book(NAME,price,birth) VALUES(?,?,'2016-5-8 19:23:10')";//有没有分号都一样
PreparedStatement ps=con.prepareStatement(sql);
for(int i=0;i<5;i++){
ps.setString(1, "大话西游");
ps.setDouble(2, 100.5);
ps.addBatch();
}
int[] nums=ps.executeBatch();
for(int i=0;i
这是Connect工具类(单例))
package cn.hncu.utils;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class ConnectFactory {
private static Connection con=null;
static{
try {
Properties p=new Properties();
p.load(ConnectFactory.class.getClassLoader().getResourceAsStream("jdbc.properities"));
String url=p.getProperty("url");
String user=p.getProperty("user");
String password=p.getProperty("password");
con=DriverManager.getConnection(url, user, password);
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getCon(){
return con;
}
public static void main(String[] args) {
System.out.println(getCon());
}
}