码迷,mamicode.com
首页 > 数据库 > 详细

Java JDBC连接MYsql

时间:2019-01-06 00:00:02      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:oca   nbsp   关闭   except   statement   exe   har   mysql   char   

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(); } }

 

Java JDBC连接MYsql

标签:oca   nbsp   关闭   except   statement   exe   har   mysql   char   

原文地址:https://www.cnblogs.com/im9527/p/10226721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!