package cn.itcast.jdbc.test;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import org.junit.Test;
import cn.itcast.jdbc.util.JdbcUtil;
import com.mysql.jdbc.Connection;
public class TestJDBC {
@Test
//使用driver接口的mysql实现类连接mysql数据库
public void testOne(){
try {
java.sql.Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/dbtest";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "root");
Connection conn = (Connection) driver.connect(url, info);
System.out.println(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
//采用forName
public void testThree(){
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/dbtest";
Connection conn = (Connection) DriverManager.getConnection(url, "root", "root");
Statement state = conn.createStatement();
ResultSet rs = state.executeQuery("select * from users");
while(rs.next()){
String id = rs.getString(1);
String name = rs.getString(2);
String pwd = rs.getString(3);
System.out.println(id + name + pwd);
}
System.out.println(conn.getAutoCommit());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
//采用注册驱动的方式
public void testFour(){
try {
String url = "jdbc:mysql://localhost:3306/dbtest";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "root");
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection conn = (Connection) DriverManager.getConnection(url, info);
System.out.println(conn);
Statement state = conn.createStatement();
String sql = "insert into users(id,name,pwd) values('U123','mic','123456')";
String sql2 = "delete from users where id='U123'";
state.execute(sql2);
state.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}