1.什么是jdbc,作用是什么?
Java Datebase Connecontion 作用是连接Java和数据库
2.jdbc操作数据库的步骤
public class P1 {
public static void main(String[] args) throws Exception{
//导入jar包后
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接、数据库地址url,用户名,密码
String url="jdbc:mysql://192.168.190.2:3306/bank";
Connection conn= DriverManager.getConnection(url, "root", "ok");
//3.执行增删改查等操作
Statement stat = conn.createStatement();
String sql1="insert into account values(4,'HANMEIMEI',6000)";
stat.executeUpdate(sql1); //除了查询都用executeUpdate()
String sql2="select * from account";
ResultSet rs = stat.executeQuery(sql2);
while(rs.next()){
System.out.println(rs.getString(1));
// int i=1;
// while(i<=rs.getMetaData().getColumnCount()){
// System.out.print(rs.getObject(i) + "\t|");
// i++;
// }
// System.out.println();
}
//4.关闭资源
rs.close();
stat.close();
conn.close();
}
}
3.Statemnt和PreparedStatement的区别
PreparedStatement可以过滤任何把条件变为全局的sql语句,更加安全
4.PreparedStatement方法演示
public class TestPrepared {
private static Connection conn;
private static PreparedStatement pst;
private static ResultSet rs;
private static final String URL="jdbc:mysql://192.168.190.2:3306/test";
public static void getConn(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
if(conn==null)//防止关闭之前二次调用再次连接地址变更
conn = DriverManager.getConnection(URL, "root", "ok");
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void query(String sql,String... params){
try {
pst=conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pst.setObject(i+1,params[i]);
}
rs=pst.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static boolean update(String sql,String... params){
int num=0;
try {
pst=conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pst.setObject(i+1,params[i]);
}
num=pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return num>0;
}
public static void close(){
try {
if(null!=rs)
rs.close();
if(null!=pst)
pst.close();
if(null!=conn)
conn.close();
}catch (SQLException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
getConn();
// String sql="select * from subject where subjectNo=?";
// query(sql,"3");
// while(rs.next()){
// int i=1;
// while (rs.getMetaData().getColumnCount() >= i) {
// System.out.print(rs.getObject(i)+"\t|");
// i++;
// }
// System.out.println();
// }
String sql="update subject set SubjectName='HTML' where ClassHour>? and GradeID between ? and ?";
boolean isCorrect = update(sql,"110","1","3");
System.out.println(isCorrect?"插入成功":"插入失败");
}
}