JDBC连接步骤:
1.加载驱动//Class.forName(className);
2.配置网络,IP端口,用户密码,数据库名,获取链接即url、username、password等信息
3.获取Connection对象连接://DriverManager//连接驱动管理
写一个sql语句命令
4.发送命令执行5.执行后结果6.得到的结果集
7.结果集要有映射类 8.遍历结果集
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DButil {//链接数据库
private static String url=null;
private static String username=null;
private static String password=null;
private static Connection conn;
static String className;
static {
try {
Properties properties=new Properties();
InputStream in=DButil.class.getClassLoader().getResourceAsStream("db.properties");
properties.load(in);
url=properties.getProperty("url");
username=properties.getProperty("username");
className=properties.getProperty("className");
password=properties.getProperty("password");
System.out.println(url+username+className+password);
// 加载驱动
Class.forName(className);
// 获取连接
conn=DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
return conn;
}
}
1、为什么PreparedStatement的创建在异常处理的外部?
某一个代码块中的局部变量,如果声明在try语句块中只能在try语句块中使用,不能用作全局变量
2、为什么要让PreparedStatement ps=null;?如果不初始化行不行?
在Java程序中局部变量,是必须要初始化,也就是要指定一个初始值,否则不能访问。
public Activity getActivityById(int aid) {
// TODO Auto-generated method stub
Activity ac = null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
ps=conn.prepareStatement("select * from activity where aid=?");
ps.setInt(1, aid);
rs=ps.executeQuery();
if(rs.next()) {
ac=new Activity(aid,
rs.getString("imgurl"),
rs.getTimestamp("starttime"),
rs.getTimestamp("endtime"),
rs.getInt("totalpeople"),
rs.getInt("totaltickets"),
rs.getInt("totalaccess"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
ps.close();
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return ac;
}