JDBC连接Mysql数据库简单实例
1、引入mysql-connector-java包
Maven方法如下
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
简单示例代码:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestConnectMysql { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { //指定连接类型 Class.forName("com.mysql.jdbc.Driver").newInstance(); //通过JDBC连接串获取连接 connection = DriverManager.getConnection("jdbc:mysql://localhost/mydata?user=root&password=123456"); statement = connection.createStatement(); //准备执行语句 resultSet = statement.executeQuery("select * from dept"); while (resultSet.next()) { System.out.println(resultSet.getString("loc")); } } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { //关闭连接 try { if (resultSet != null) { resultSet.close(); resultSet = null; } if (statement != null) { statement.close(); statement = null; } if (connection != null) { connection.close(); connection = null; } } catch (SQLException e2) { e2.printStackTrace(); } } } }
欢迎大家多多评论指正和转载,转载请注明出处………