java连接mysql问题小结

来源:互联网 发布:照片扫描软件手机版 编辑:程序博客网 时间:2024/06/01 18:13

    很多Java程序都有用到连接MySQL数据库,本篇文章介绍java与mysql数据库建立连接并进行简单数据交互。  

    下载mysql-connector-java-5.1.26-bin.jar驱动完成后,将下载好的mysql-connector-java-5.1.26-bin.jar拷贝至项目目录下。找到项目文件夹下的referencedlibraries 右键bulid path 后configure build path 选择add external jars 最后找到下载好的jar文件即可。此时驱动即引入成功。

    给出范例代码:

package Dao;import java.sql.*;public class JDBCTest {public static void main(String[] args) {String driver = "com.mysql.jdbc.Driver";// 驱动程序名String url = "jdbc:mysql://127.0.0.1:3306/javaprogram";    //url指向要访问的数据库 此时的javaprogram 为笔者创建的数据库 String user = "root";   // MySQL配置时的用户名String password = "密码";  // MySQL配置时的密码  更改成自己的密码即可try {// 加载驱动程序Class.forName(driver);System.out.println("驱动加载成功!");// 连接数据库Connection conn = DriverManager.getConnection(url, user, password);if (!conn.isClosed())System.out.println("成功连接数据库!");// statement用来执行SQL语句//更新语句Statement statement = conn.createStatement();            String updatesql="update user set userpwd='123' where user='zwy'";            statement.executeUpdate(updatesql);              //插入语句        /*String insertsql="insert into user (user,userpwd) values ('小胖','xiaopang')";        statement.clearBatch();        statement.addBatch(insertsql);        statement.executeBatch();*/// 查询语句String selectsql = "select * from user ";// 结果集ResultSet rs = statement.executeQuery(selectsql);String name = null;while (rs.next()) {name = rs.getString("user");System.out.println(name+ "\t" +rs.getString("userpwd") ); }rs.close();conn.close();} catch (ClassNotFoundException e) {System.out.println("Sorry,can`t find the Driver!");e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}}

    以上即为连接mysql数据库最为基础的代码。包括了连接方式和一些简单的插入数据、更新数据和查询数据案例,在此不过多赘述。

    若在连接时出现Access denied for user 'root'@'localhost' (using password: YES)异常,则说明是密码错误。此时打开mysql在查询界面输入下列代码执行即可。

grant all privileges on *.* to 'root'@'localhost' identified by '你设置的密码' with grant option;flush privileges  
   出现其他的问题也可自行查找解决方案。


0 0
原创粉丝点击