2017年12月21日 22:40:31
?占位符
ps=connect.prepareStatement();//准备声明
ps.excuteUpdate(SQL语句);
package com.bdqn.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.bdqn.entity.Dmp;
public class Test {
public static void main(String[] args) {
Connection connection=null;//连接
Statement statement=null;//声明
ResultSet rs=null;//结果集
PreparedStatement ps=null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//url 用户名 密码
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/school", "root", "root");
System.out.println("连接数据库成功了。");
//生命=连接。新建声明
statement=connection.createStatement();
/*ps.setDate(2, new java.sql.Date(new Date().getTime()));*/
String insertintoString="insert into Emp(eId,eName,eAge,eBrithday,eHobby) values(?,?,?,?,?)";
ps=connection.prepareStatement(insertintoString);
ps.setInt(1, 7);
ps.setString(2, "zhanogksan");
ps.setInt(3, 81);
ps.setString(4, "2016-3-25");
ps.setString(5, "dilanuhiu");
int numm=ps.executeUpdate();
System.out.println(numm);
if(numm>0){
System.out.println("插入成功。");
}
//增加
/*String str1="insert into Emp values(6,'caoaman',20,'2017-12-20','aman')";
boolean flag1=statement.execute(str1);
if(!flag1){
System.out.println("增加成功");
}else{
System.out.println("增加失败。");
}*/
//修改
/*String str2="update Emp set eName='lisi' where eId=1";
statement.execute(str2);*/
/*String str22="update Emp set eName='llipipsiip' where eId=?";
ps=connection.prepareStatement(str22);
ps.setInt(1,2);
int num=ps.executeUpdate();
System.out.println(num);
if(num==1){
System.out.println("修改成功");
}else{
System.out.println("修改失败。");
}*/
//查询
/*String str3="SELECT * FROM Emp";
rs=statement.executeQuery(str3);
List<Dmp> list=new ArrayList<Dmp>();
while (rs.next()) {
Dmp dmp=new Dmp();
int eId=rs.getInt("eId");
String eName =rs.getString("eName");
int eAge=rs.getInt("eAge");
String eBrithday =rs.getString("eBrithday");
String eHobby =rs.getString("eHobby");
dmp.seteId(eId);
dmp.seteName(eName);
dmp.seteAge(eAge);
dmp.seteBrithday(eBrithday);
dmp.seteHobby(eHobby);
list.add(dmp);
}
System.out.println("集合里多少个对象就代表该数据表里有多条数据:"+list.size());
for(Dmp d:list){
System.out.println("eId是:"+d.geteId()+"\t"+"eName是:"+d.geteName()+"\t"+"eAge是:"+d.geteAge()+"\t"+"eBrithday是:"+d.geteBrithday()+"\t"+"eHobby是:"+d.geteHobby()+"\n");
}*/
//删除
/*String str4="delete from Emp where eId=?";
ps=connection.prepareStatement(str4);
ps.setInt(1,4);
int num=ps.executeUpdate();
System.out.println(num+"行删除成功。");*/
} catch (Exception e) {
// TODO: handle exception
}finally{
try {
if (connection!=null) {
connection.close();
}
if (statement!=null) {
statement.close();
}
if (rs!=null) {
rs.close();
}
if (ps!=null) {
ps.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}