首页 > 代码库 > Java 连接 MySQL 数据库
Java 连接 MySQL 数据库
下载 MySQL 数据库:http://dev.mysql.com/downloads/mysql/ ,解压到本地即可
下载 jar 包:http://dev.mysql.com/downloads/connector/j/ ,下载 zip 压缩包
创建数据库并插入若干数据:
create table mydb; use mydb; create table student(name varchar(8), no char(7)); insert into student values(‘zhang‘, ‘011‘); insert into student values(‘li‘, ‘021‘); select * from student;
数据库连接类:
package g.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DbConnection { public static Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://127.0.0.1:3306/mydb"; Connection connection = DriverManager.getConnection(url, "root", "root"); return connection; } public static void free(Connection connection, Statement statement, ResultSet resultSet) { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
测试JDBC连接:
package g.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TestJDBC { public static void main(String[] args) { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; try { connection = DbConnection.getConnection(); String sql = "select * from student"; statement = connection.prepareStatement(sql); resultSet = statement.executeQuery(); while (resultSet.next()) { System.out.println(resultSet.getString("name") + " : " + resultSet.getString("no")); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。