package com.ljy.day20;
import org.junit.Test;
import java.sql.*;
public class TestInsertUpdateDelete {
@Test
public void testSelect() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///itheima";
String name = "root";
String password = "201223";
Connection connection = DriverManager.getConnection(url, name, password);
Statement statement = connection.createStatement();
String sql = "select id, username as name, password from user";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name1 = resultSet.getString("name");
String password1 = resultSet.getString("password");
System.out.println(id + ", " + name1 + ", "+ password1);
}
resultSet.close();
statement.close();
connection.close();
}
@Test
public void testInsert() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///itheima";
String name = "root";
String password = "201223";
Connection connection = DriverManager.getConnection(url, name, password);
Statement statement = connection.createStatement();
String uname = "熊大111";
String upwd = "123456";
String sql = "insert into user(username, password) values ('"+uname + "', '" + upwd + "')";
int i = statement.executeUpdate(sql);
if(i > 0) {
System.out.println("用户添加成功!!");
}
statement.close();
connection.close();
}
@Test
public void testUpdate() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///itheima";
String name = "root";
String password = "201223";
Connection connection = DriverManager.getConnection(url, name, password);
Statement statement = connection.createStatement();
String sql = "update user set username = '熊二' where id = 4";
int i = statement.executeUpdate(sql);
if(i > 0) System.out.println("用户修改成功!!");
statement.close();
connection.close();
}
@Test
public void testDelete() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql:///itheima";
String name = "root";
String password = "201223";
Connection connection = DriverManager.getConnection(url, name, password);
Statement statement = connection.createStatement();
String sql = "delete from user where id = 4";
int i = statement.executeUpdate(sql);
if(i > 0) System.out.println("用户删除成功!");
statement.close();
connection.close();
}
}