import java.sql.*; public class test { public static void main(String args[]) { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306"; String user = "root"; String password = "123123"; try { Class.forName(driver); Connection connection = DriverManager.getConnection(url, user, password); if (!connection.isClosed()) { System.out.println("Succeeded in connecting to the Database!"); Statement statement = connection.createStatement(); String sql = "SET NAMES `utf8`"; statement.executeUpdate(sql); sql = "USE `mydatabase`"; statement.executeUpdate(sql); sql = "SELECT * FROM `mytable`"; ResultSet result_set = statement.executeQuery(sql); while(result_set.next()) { String name = result_set.getString("first"); System.out.println(name); } result_set.close(); connection.close(); } }catch(Exception ex) { ex.printStackTrace(); } } } |
编译时要将MySQL的jdbc驱动放到与java源文件同目录下。