package jdbc;
import java.sql.*;
/**
* @author :KSea
*/
public class TestJDBC {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
//1.初始化驱动
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库加载成功");
//2.与数据库连接
connection = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/ksea?characterEncoding=UTF-8",
"root",
"root");
System.out.println("Connection Success! Connect object:" + connection);
//3.创建执行sql语句的对象
statement = connection.createStatement();
System.out.println("" + statement);
//4.编写sql语句,执行它
//增
String sql_add = "insert into hero values(null,"+"'test'"+","+45+")";
//statement.execute(sql_add);
//删
String sql_del = "delete from hero where name = 'test'";
//statement.execute(sql_del);
//改
String sql_upadate = "update hero set name = 'updata_name' where name = 'test'";
//statement.execute(sql_upadate);
//查,通过ResultSet来接收结果
String sql_select = "select name from hero";
Boolean execute = statement.execute(sql_select);
if (execute) {
ResultSet resultSet = statement.getResultSet();
while (resultSet.next()) {
System.out.println(resultSet.getString("name"));
}
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
//5.关闭资源
finally {
try {
connection.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}