先新建Java 工程,将jar包导进去:
然后新建相应的数据库和表。
编写DBUtil.java
1 package com.study.db; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.Statement; 7 8 public class DBUtil { 9 10 private static final String URL="jdbc:mysql://localhost:3306/demo_jdbc"; 11 private static final String NAME="root"; 12 private static final String PASSWORD="root"; 13 14 public static void main(String[] args) throws Exception{ 15 16 //1.加载驱动程序 17 Class.forName("com.mysql.jdbc.Driver"); 18 //2.获得数据库的连接 19 Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD); 20 //3.通过数据库的连接操作数据库,实现增删改查 21 Statement stmt = conn.createStatement(); 22 ResultSet rs = stmt.executeQuery("select user_name,age from imooc_goddess");//选择import java.sql.ResultSet; 23 while(rs.next()){//如果对象中有数据,就会循环打印出来 24 System.out.println(rs.getString("user_name")+","+rs.getInt("age")); 25 } 26 } 27 }