package JDBC_1;标签:jdbc,java,String,resultSet,JDBC,sql,import From: https://www.cnblogs.com/qin99/p/16795168.html
import com.mysql.cj.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBC1 {
//目标:为了在类中获取在数据库中的数据
public static void main(String[] args) throws Exception {
String host = "127.0.0,1";
String port = "3306";
String username = "root";
String password = "root";
//注册MYsql的驱动器
Class.forName("com.mysql.cj.jdbc.Driver");
//2.通过驱动器获得MYsql的连接
//jdbc数据库URL的构成 jdbc:mYsql://ip地址:端口号/数据库名:jdbc_4
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jdbc_4",
username,
password);
System.out.println(connection);
//3:操作数据库
//3.1查询
String sql = "select * from user";
//sql操作器
//获取sql操作器
Statement statement = connection.createStatement();
//3.3使用操作器执行查询并获取结果集
ResultSet resultSet = statement.executeQuery(sql);
//3.4解析结果集
System.out.println("id \t nane \tphone");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String nane = resultSet.getString("nane");
String phone = resultSet.getString("phone");
System.out.println(id + "\t" + nane + "\t" + phone);
}
}
}