ITPub博客

首页 > 移动开发 > 移动测试 > 深圳软件测试培训学习:Java连接MySQL--【千锋】

深圳软件测试培训学习:Java连接MySQL--【千锋】

原创 移动测试 作者:andy888168 时间:2019-11-04 15:11:44 0 删除 编辑

深圳软件测试培训学习: Java 连接 MySQL -- 【千锋】

Java 使用 JDBC 连接MySQL 数据库 需要驱动包 。

最新版下载地址为: http://dev.mysql.com/downloads/connector/j/ ,解压后得到jar 库文件, 然后在对应的项目中导入该库文件。

1. 创建测试数据

在 MySQL 中创建表 , 表结构如下:

create table `w` (

`id` int(11) not null auto_increment,

`name` char(20) not null,

`url` varchar(255) not null,

primary key (`id`)

) engine=innodb default charset=utf8;

insert into `w` values ('1', 'google', 'https://www.google.cm/');

insert into `w` values('2', ' 淘宝 ', 'https://www.taobao.com/');

2. 连接数据库

package com. run .test;

import java.sql.*;

public class MySQLDemo {

    // JDBC 驱动名及数据库 URL

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  

    static final String DB_URL = "jdbc:mysql://localhost:3306/ sss " ;

    // 数据库的用户名与密码,需要根据自己的设置

    static final String USER = "root";

    static final String PASS = "123456";

    public static void main(String[] args) {

        Connection conn = null;

        Statement stmt = null;

        try{

            // 注册 JDBC 驱动

            Class.forName(JDBC_DRIVER);  

            // 打开链接

            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            // 执行查询

            stmt = conn.createStatement();

            String sql;

            sql = "SELECT name, url FROM w";

            ResultSet rs = stmt.executeQuery(sql);

            // 展开结果集数据库

            while(rs.next()){

                // 通过字段检索

                String name = rs.getString("name");

                String url = rs.getString("url");

                // 输出数据

                System.out.print(" 站点名称 : " + name);

                System.out.print(" 站点 URL: " + url);

                System.out.print("\n");

            }

            // 完成后关闭

            rs.close();

            stmt.close();

            conn.close();

        }catch(SQLException se){

            // 处理 JDBC 错误

            se.printStackTrace();

        }catch(Exception e){

            // 处理 Class.forName 错误

            e.printStackTrace();

        }finally{

            // 关闭资源

            try{

                if(stmt!=null) stmt.close();

            }catch(SQLException se2){

            }            

try{

                if(conn!=null) conn.close();

            }catch(SQLException se){

                se.printStackTrace();

            }

        }

    }

}

以上实例执行输出结果如下:

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69947096/viewspace-2662533/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
莫安迪分享各类资讯文章

注册时间:2019-09-02

  • 博文量
    69
  • 访问量
    43789