周六闲来无事看了看以前的代码,在java中如何调用数据源
大概看了有两种方式:
1.原始的jdbc
String url = "jdbc:mysql://localhost:3306/test";
String user = "ODBC";
String password = "";
String sql = "select * from stu";
String sql2 = "insert into stu(name, age, gender) values('aaa', 25, 'female')";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try
{
//1.加载并注册数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建数据库的连接
con = DriverManager.getConnection(url, user, password);
//3.分配一个Statement对象
stmt = con.createStatement();
//4.stmt执行sql语句
rs = stmt.executeQuery(sql);//只执行查询,且将查询结果赋予rs
// int flag = stmt.executeUpdate(sql2);//表示对增删改sql语句的执行方法,返回受影响的行数
// if(flag == 0)
// {
// System.out.println("failure");
// }
// else
// {
// System.out.println("success");
// }
//5.取得从数据库中得到的值
while(rs.next())
{
// int id = rs.getInt("id");
// String name = rs.getString("name");
// String gender = rs.getString("gender");
// int age = rs.getInt("age");
int id = rs.getInt(1);
String name = rs.getString(2);
String gender = rs.getString(4);
int age = rs.getInt(3);
logger.info(id + " " + name + " " + age + " " + gender);
}
}
catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
//6.关闭相应的JDBC对象,按照使用相反的顺序关闭
if(rs != null)
{
try
{
rs.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt != null)
{
try
{
stmt.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con != null)
{
try
{
con.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
注:实际中最好把相关的配置信息写在配置文件中,这样便于维护
2.中SSH项目中在applicationContext.xml中配置
ApplicationContext ctx = new ClassPathXmlApplicationContext("配置文件"); //读取spring配置文件,生成Spring上下文环境
DataSource ds = (DataSource)ctx.getBean("dataSource");
Connection connection = = ds.getConnection();
Statement stmt = conn.createStatement();// 创建执行语句对象
ResultSet rs = stmt.executeQuery(sql);// 执行sql语句,返回结果集
while(rs.next()) {
if(rs.getString(2) != null){
notice += rs.getString(2);//加载信息
}
}
rs.close(); // 关闭结果集
stmt.close(); // 关闭执行语句对象
conn.close(); // 关闭与数据库的连接