java 中 JDBC 连接数据库操作

来源:互联网 发布:淘宝进口商品资质 编辑:程序博客网 时间:2024/06/15 15:59

首先新建一个java工程 工程名随便取
注意!:博主用的是Mysql数据库 如不同则自行下载相应驱动包
【Mysql驱动包下载】
环境搭配(博主用的Eclipse):下载解压后找到mysql-connector-java-5.1.44-bin.jar需要在工程中导入该库文件
选中java工程右击选择Build Path–>Configure Build Path…
Build Path
点击Add External JARs 找到之前的mysql-connector-java-5.1.44-bin.jar文件选中点击完成
点击Apply 点击ok完成导入(导入好了会看到库文件已经在我们的工程下面了)
add external
当然如果你不想要这么麻烦你可以直接新建一个lib文件夹与src在同一级目录下然后将库文件拷贝到lib目录下同样可行

代码部分:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class Sql {String driver = "com.mysql.jdbc.Driver";//驱动路径    static String url = "jdbc:mysql://127.0.0.1:3306/xuexi";//连接数据库名    static String user = "你的name";//用户名    static String password = "你的pass";//密码    public static void main(String[] args) {        // 第一步:加载驱动            try {                Class.forName(driver);            } catch (ClassNotFoundException e1) {                e1.printStackTrace();            }        // 第二步:获取连接        Connection conn = null;        try {            conn = (Connection) DriverManager.getConnection(url, user, password);        } catch (SQLException e) {            e.printStackTrace();        }        // 第三步:创建处理对象        Statement statement = null;        try {            statement = (Statement) conn.createStatement();        } catch (SQLException e) {            e.printStackTrace();        }        //第四步:编写要执行的sql语句        String sql = "select * from 表名";        //第五步:执行sql语句        ResultSet  res=null;        try {            res = statement.executeQuery(sql);            while(res.next()){                System.out.println(res.getString("name"));            }        } catch (SQLException e) {            e.printStackTrace();        }        res.close();//关闭ResultSet对象        statement.close();//关闭Statement对象        conn.close();//关闭Connection对象    }}

本文章只提拱了与mysql数据库连接后续会提供与其它数据库连接的操作。

原创粉丝点击