JDBC首日
package com.neuedu.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 将customer表中的记录查询出来打印在控制台
* @author Administrator
*/
public class JDBCDemo1 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
// 1.将数据库驱动包导入项目
try {// 2.加载数据库驱动程序(将驱动程序加载到JVM内存里)
Class.forName("com.mysql.jdbc.Driver");// 3.利用驱动管理器类,获取数据库连接对象Connection(java.sql)
// url : jdbc:mysql://[主机ip:端口号]/数据库名称
// localhost本地,自己ip,127.0.0.1
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/java19_mul", "root", "root");
// 4.利用数据库连接对象,获取SQL语句对象PreparedStatement(java.sql)
String sql = "select * from customer";
ps = conn.prepareStatement(sql);// 5.调用PreparedStatement对象的查询方法,得到结果集对象
rs = ps.executeQuery();
// 循环遍历
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println(id+","+name+","+age);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}