package com.imooc.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/** * */public class DBUtil { private final static String URL="jdbc:mysql://127.0.0.1:3306/imooc?useUnicode=true&characterEncoding=utf-8"; private final static String PASSWORD="1234"; private final static String USER="root"; public static void main(String[] args) throws ClassNotFoundException, SQLException { //1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2.获得数据库驱动 Connection con = DriverManager.getConnection(URL,USER,PASSWORD); //3.通过数据库连接操纵数据库,实现增删该查 Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select user_name,age from imooc_goddess"); while(rs.next()){ System.out.println(rs.getString("user_name")+","+rs.getInt("age")); } }} 刚开始遇到了Access denied for user ‘1234‘@‘localhost‘ (using password: YES)的问题,仔细一检查才发现密码和用户名写反了,改过来立马能运行了,要注意的是
Connection,Statement,ResultSet三个要导入的包是java.sql.*下的,而不是com.mysql.jdbc.*下的。
时间: 2024-10-11 20:53:17