上一篇《JDBC编程入门》对理论知识进行了详细的说明,此处则对代码进行演示。
package com.wrh.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
import com.mysql.jdbc.StreamingNotifiable;
/**
* <p>
*
* </p>
* @Copyright (C),
* @author hero_wrh
* @Date:2018年8月6日
* JDBC
*/
public class JDBC01 {
Connection con;
Statement stmt;
public static Connection getConnection() throws ClassNotFoundException, SQLException {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/student";
String username="root";
String pwd="123456789";
//获取连接
Connection con = DriverManager.getConnection(url, username, pwd);
return con;
}
//插入
@Test
public void insert() throws ClassNotFoundException, SQLException{
try {
con = getConnection();
stmt = con.createStatement();
String sql = "insert into test values('lisi', '23')";
stmt.execute(sql);
System.out.println("插入成功");
} catch (Exception e) {
// TODO: handle exception
}finally {
stmt.close();
con.close();
}
}
//修改
@Test
public void update() throws ClassNotFoundException, SQLException {
try {
con = getConnection();
stmt = con.createStatement();
String sql="update test set age='18' where age='23'";
stmt.executeUpdate(sql);
System.out.println("修改成功");
} catch (Exception e) {
// TODO: handle exception
}finally {
stmt.close();
con.close();
}
}
//删除
@Test
public void delete() throws SQLException, ClassNotFoundException {
try {
con = getConnection();
stmt = con.createStatement();
String sql = "delete from test where name='lisi'";
stmt.executeUpdate(sql);
System.out.println("删除成功!");
} catch (Exception e) {
// TODO: handle exception
}finally {
stmt.close();
con.close();
}
}
//查询
@Test
public void query() throws SQLException, ClassNotFoundException {
try {
con = getConnection();
stmt = con.createStatement();
String sql = "select * from test";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
String name = rs.getString(1);
String age = rs.getString(2);
System.out.println(name + ", " + age);
}
System.out.println("查询成功");
} catch (Exception e) {
// TODO: handle exception
}finally {
stmt.close();
con.close();
}
}
}