package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Demo_main {
public static void main(String[] args){
PreparedStatement ps = null;
Connection c =null;
try {
//加载驱动类
Class.forName("com.mysql.jdbc.Driver");
//建立连接
c = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc的使用","root","root");
//执行SQL语句
String str ="select * from student where age>?";
ps = c.prepareStatement(str);
ps.setObject(1, 18);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
System.out.println("id="+rs.getInt(1)+" 姓名="+rs.getString(2)+" age="+rs.getString(3));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//关闭,每一个关闭之前都要判断是否为空,且要分开捕获其异常,关闭顺序为早开起的后关闭,后开始的早关闭
try {
if(ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(c != null) {
c.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
4.批处理的基本用法
最新推荐文章于 2020-06-10 17:05:53 发布