您的位置:首页 > 编程语言 > Java开发

JavaWeb JDBC初步连接和JDBC连接规范化

2014-11-03 07:41 211 查看
感谢传智播客提供的学习视频 ,希望传智播客越来越好

package cn.itcast.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

public class JdbcAddDelUpDeome {
@Test
public void DoJdbc() throws ClassNotFoundException, SQLException {
/*
* 一:得到Connection对象
*    1〉准备四大参数
*    2〉加载驱动类
*    3〉得到Connection
*/
//初始化四大参数
String driverClassName="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/db3";
String userName="root";
String passWord="123";
//加载驱动类(为了兼容性)
Class.forName(driverClassName);
//得到连接对象
Connection con = DriverManager.getConnection(url,userName,passWord);
//System.out.println(con);
//使用连接对象得到,语句发送器(statement)
Statement stment = con.createStatement();
// String sqlString="insert into student values('feifei',201405,'man','wenyuan')";
String sqlupdate ="update student set UserName ='FeiFei' where UserCode =201405";
//使用语句发送器对象的executeUpdate()方法来执行语句,并返回影响行数,insert,delete,update,不包括查询语句
int num=stment.executeUpdate(sqlupdate);
System.out.println(num);

}
/**
* 执行查询
* @throws ClassNotFoundException
* @throws SQLException
*
*/
@Test
public void SelectTable() throws ClassNotFoundException, SQLException{
/**
* 带规范化的JDBC写法(try catch,finally)
*/
//初始化参数,因为,try, catch,finally几个代码块中都会用到公用的参数,所以要公用出来
Connection con =null;
Statement stmt =null;
ResultSet rs =null;
try{
// 一:配置四大参数
String driverClassName ="com.mysql.jdbc.Driver";
String url ="jdbc:mysql://localhost:3306/db3";
String userName="root";
String passWord="123";
// 1 加载驱动类
Class.forName(driverClassName);
//2  通过剩下的三个参数,调用 driverManger的getConnection(),得到连接
con =DriverManager.getConnection(url,userName,passWord);
/**
* 二,得到Statement,执行select语句
*/
// 1得到 Statement对象,用Connection的createStatement()方法
stmt=con.createStatement();
// 2调用 statement的executeQuery方法来得到一个查询结果集
rs=stmt.executeQuery("select * from student");
/**
* 三:解析ResultSet上的数据(表)
* 调用ResultSet中的next()方法,来移动到下一行,有数据返回true ,没有数据返回false
*
*/
while(rs.next()){
String username= rs.getString("UserName");
int usercode = rs.getInt("UserCode");
String usersex = rs.getString("UserSex");
//输出测试语句
System.out.println(username+" "+usercode+" "+usersex);
}
}catch(Exception e){
throw new  RuntimeException(e);
}
finally{
/**
* 四,关闭资源流
*  倒关:先写的后关
*/
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(con!=null){
con.close();
}

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: