Java JDBC连接MYsql

2019-01-08 08:22:50来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
    public static void Query() {
        Connection connection = null;
        try {
            String SDdriver = "com.mysql.jdbc.Driver";
            String SDurl = "jdbc:mysql://localhost:3306/emsdb?characterEncoding=utf8&useSSL=true";
       //emsdb替换成自己的数据库名称 String SDuser
= "root"; String SDpassword = "123456"; Class.forName(SDdriver); connection = DriverManager.getConnection(SDurl, SDuser, SDpassword); } catch (Exception e) { e.printStackTrace(); } PreparedStatement preparedStatement = null; ResultSet resultSet = null; String ss = new String("SELECT * from employer;"); try { preparedStatement = connection.prepareStatement(ss); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { System.out.println(resultSet.getString("ename")); } } catch (SQLException ex) { } finally { closeAll(connection, preparedStatement,resultSet); } } public static void closeAll(Connection connection, PreparedStatement preparedStatement,ResultSet resultSet) { try {
       //按顺序关闭
if(resultSet!=null) { resultSet.close(); } if (preparedStatement!=null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub Query(); } }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:java基础:JDK环境安装

下一篇:MVC是什么?