package groovy
import groovy.sql.Sql
//def sql = Sql.newInstance('jdbc:mysql://localhost:3306/day01?serverTimezone=GMT%2B8', 'root', 'root', 'com.mysql.cj.jdbc.Driver')
//sql.connection.autoCommit=false
//def sqlstr = """
// insert into article(title,content,price,create_time) values ("感恩节","今天是感恩节!","35","20191130")
//"""
//try{
// sql.execute(sqlstr)
// sql.commit()
// println("Successfully committed")
//}catch(Exception ex){
// sql.rollback()
// println("Transaction rollback")
//}finally {
// println("向数据表中添加数据")
//}
//sql.close()
//添加操作
//def sql = Sql.newInstance('jdbc:mysql://localhost:3306/day01?serverTimezone=GMT%2B8', 'root', 'root', 'com.mysql.cj.jdbc.Driver')
//sql.connection.autoCommit=false
//def title="星期五"
//def content="今天是星期五"
//def price="22"
//def create_time="20191130"
//def sqlstr="insert into article(title,content,price,create_time) values ('$title','$content','$price','$create_time')"
//try{
// sql.execute(sqlstr)
// sql.commit()
// println("Sucessfully commited")
//}catch(Exception ex){
// sql.rollback()
// println("Transaction rollback")
//}
//sql.close()
//查询操作
//def sql=Sql.newInstance("jdbc:mysql://localhost:3306/day01?serverTimezone=GMT%2B8","root","root","com.mysql.cj.jdbc.Driver")
//sql.eachRow("select * from article"){
// tp->
// println([tp.title,tp.content,tp.price,tp.create_time])
//}
//sql.close()
//更改操作
//def sql=Sql.newInstance("jdbc:mysql://localhost:3306/day01?serverTimezone=GMT%2B8","root","root","com.mysql.cj.jdbc.Driver")
//def sqlstr="update article set create_time=20191129 where id=4"
//try{
// sql.execute(sqlstr)
// sql.commit()
// println("update sucessfully")
//}catch(Exception ex){
// sql.rollback()
// println("Transaction rollback")
//}finally{
// println("修改成功")
// sql.close()
//}
//删除
def sql=Sql.newInstance("jdbc:mysql://localhost:3306/day01?serverTimezone=GMT%2B8","root","root","com.mysql.cj.jdbc.Driver")
def sqlstr="delete from article where id=4"
//如果添加这句,则必需要执行:sql.commit()才能成功执行sql语句
sql.connection.autoCommit=false
try{
sql.execute(sqlstr)
sql.commit()
println("删除成功!")
}catch(Exception ex){
sql.rollback()
println("回滚")
}finally{
sql.close()
}
环境配置:
添加mysql对应版本的jdbc,jar包
2:jar包添加方法:
ctrl+shift+alt+s->