首页 > 代码库 > Java连接mysql数据库
Java连接mysql数据库
在java中连接mysql数据库,先要下载mysql驱动mysql-connector-java-5.1.30.zip,解压出.jar文件复制到项目目录中,再Build Path即可使用。
package cn.hitech.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MysqlDemo { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName("com.mysql.jdbc.Driver"); try { connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/unit", "root", "adminsa"); if (connection != null && !connection.isClosed()) { System.out.println("connection successfully."); statement = connection.createStatement(); statement .execute("INSERT INTO uinit(uid,uname,secret) VALUES(2,‘祁连山‘,‘secret3‘"); resultSet = statement.executeQuery("select * from uinit"); while (resultSet.next()) { System.out.println("uid" + resultSet.getString("uid")); System.out.println("uname" + resultSet.getString("uname")); System.out.println("secret" + resultSet.getString("secret")); } } } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } finally { resultSet = null; } try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } finally { connection = null; } } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。