package com.wj.demo01;
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.Driver;
public class Demo01 {
@Test
public void fun5() {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/mydb3";
String user="root";
String password="1234";
conn=DriverManager.getConnection(url, user, password);
stmt=conn.createStatement();
String sql="select * from student";
rs=stmt.executeQuery(sql);
while(rs.next()) {
int id=rs.getInt("id");
String name=rs.getString("name");
System.out.println(id+"-"+name);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}finally {
try {
if(rs!=null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(stmt!=null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Test
public void fun4() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb3";
String user = "root";
String password = "1234";
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
String sql = "update student set name='小六六' where id=4";
boolean boo = stmt.execute(sql);
if (!boo) {
int count = stmt.getUpdateCount();
System.out.println("受影响的行数是:" + count);
}
stmt.close();
conn.close();
}
@Test
public void fun3() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb3";
String user = "root";
String password = "1234";
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
String sql = "select * from student";
boolean boo = stmt.execute(sql);
ResultSet rs = null;
if (boo) {
rs = stmt.getResultSet();
while (rs.next()) {
System.out.println(rs.getInt("id") + ":" + rs.getString("name"));
}
}
rs.close();
stmt.close();
conn.close();
}
@Test
public void testJDBCHelloWorld() throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb3?useUnicode=true&characterEncoding=utf8", "root", "1234");
String sql = "select * from student";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Integer id = rs.getInt("id");
String name = rs.getString("name");
String add = rs.getString("city");
Integer age = rs.getInt("age");
System.out.println(id + ":" + name + ":" + add + ":" + age);
}
rs.close();
stmt.close();
conn.close();
}
@Test
public void fun2() {
System.out.println("hhhh");
}
@Test
public void fun1() {
System.out.println("斤斤计较");
}
}