JDBC连接MySQL

准备工作:

1. 安装好MySQL并启动服务

2. 下载 mysql-connector-java-5.1.45 (也可以通过IDEA自动下载)

连接步骤:

1. View >Tool Windows >DataBase > + > MySQL

2. 添加连接器

3. 填写下图内容并测试连接,出现 successful 就表示连接成功,第一次进入时会有填写数据库名的选项,填写过了这个名字就会消失并进入URL

 

4. 右边栏显示数据库的表结构

 

5. 表内数据显示在左边(可视界面)

表的左上角可以查询内容(按城市名查询),如过修改了内容要点击提交按钮才能真正提交至数据库

6. java操作数据库,先要导入MySQL的驱动包,具体操作代码如下:

 

import java.sql.*;


public class JDBCtest {
    static final String driver = "com.mysql.jdbc.Driver";
    static final String url = "jdbc:mysql://localhost:3306/yiibaidb";
    static final String user ="root";
    static final String password ="123";
    public static void main(String[] args) {
        Connection con=null;
        try
        {
            //加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            //1. getConnection()方法,连接MySQL数据库,指明连接对象
            con = DriverManager.getConnection(url,user,password);
            if(!con.isClosed()){
               System.out.println("Succeeded connecting to the Database!");
}
//2.创建statement类对象,用来执行SQL语句 Statement statement = con.createStatement(); String sql = "select city from yiibaidb.offices";
//3.创建ResultSet类,用来存放获取的数据结果集 ResultSet rs = statement.executeQuery(sql); System.out.println("---------------"); System.out.println("执行结果如下所示:"); System.out.println("---------------"); System.out.println(" 城市" + "\t" ); System.out.println("---------------"); String city = null; while(rs.next()) { //获取city这列数据 city = rs.getString("city"); System.out.println(city + "\t" ); } rs.close(); con.close(); } catch(ClassNotFoundException e) { //数据库驱动类异常处理 System.out.println("Sorry,can`t find the Driver!"); e.printStackTrace(); } catch(SQLException e) { //数据库连接失败异常处理 e.printStackTrace(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { System.out.println("数据库数据成功获取!!"); } } }

补充:

二者的区别:

MySQL的基础操作就不讲了,实例数据库和简易教程参考:

http://www.yiibai.com/mysql/how-to-load-sample-database-into-mysql-database-server.html

https://segmentfault.com/a/1190000006876419

https://github.com/jaywcjlove/mysql-tutorial

posted @ 2018-01-30 17:30  挑灯看剑l  阅读(196)  评论(0)    收藏  举报