您的位置:首页 > 其它

jdbc

2016-02-08 12:18 344 查看
//因为使用了JUnit,所以,先要 JUnit

//步骤:反键-->build path -->configure build path --> Libraies   --> Add Libraies,选中JUnit,然后选择JUnit4就可以了

//因为重复连接和一定要关闭连接,所以,将它们提出到一个类DBUtil中,代码在后面

package jdbc.mysql.shu01;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;

import org.junit.Test;

public class TestCase {

/**
* 查询
*/
//@Test
public void testSelect(){
String sql = "select id,name,sal,empno,deptno,job,mgr from emp";
Connection conn = null;
try {
conn = DBUtil.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt("id")+","+rs.getString("name")+","+rs.getInt("sal")+","+rs.getInt("empno")+","+rs.getInt("deptno")+","+rs.getInt("mgr"));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
DBUtil.close(conn);
}
}

/*
* 插入
*/
//@Test
public void testInsert(){
String sql = "insert into emp (id,name,sal,empno,deptno,job,mgr) values(1003,'Alice',4000,3127,30,'Clerk',6124) ";
Connection conn = null;
try {
conn = DBUtil.getConnection();
Statement st = conn.createStatement();
int i = st.executeUpdate(sql);
System.out.println(i);

} catch (Exception
4000
e) {
e.printStackTrace();
}finally{
DBUtil.close(conn);
}
}

/**
* 更新
*/
//@Test
public void testUpdate(){
String sql = "update emp set sal = 4500 where id = '1003'";
Connection conn = null;
try {
conn = DBUtil.getConnection();
Statement st = conn.createStatement();
boolean i = st.execute(sql);
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}finally{
DBUtil.close(conn);
}
}

/*
* 删除
*/
//@Test
public void testDelete(){
String sql = "delete from emp where name = 'Alice' ";
Connection conn = null;
try {
conn = DBUtil.getConnection();
Statement st = conn.createStatement();
int i = st.executeUpdate(sql);
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
}

}

package jdbc.mysql.shu01;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class DBUtil {

public static Connection getConnection(){
Connection conn = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.建立连接
String url = "jdbc:mysql://localhost:3306/t_chat";
String user = "root";
String pwd = "root";
conn = DriverManager.getConnection(url,user,pwd);

return conn;

} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}

public static void close(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

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