首页 > 数据库技术 > 详细

JDBC连接MYSQL

时间:2019-01-17 23:38:05      阅读:288      评论:0      收藏:0      [点我收藏+]
package org.spring.springboot.controller;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JDBCTest {
public static void main(String[] args) throws Exception {
Connection connection = null;
PreparedStatement prepareStatement = null;
ResultSet rs = null;

    try {
        // 加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/mytest";
        String user = "root";
        String password = "123456";
        connection = DriverManager.getConnection(url, user, password);
        // 获取statement,preparedStatement
        String sql = "select * from users where id=?";
        prepareStatement = connection.prepareStatement(sql);
        // 设置参数
        prepareStatement.setLong(1, 1l);
        // 执行查询
        rs = prepareStatement.executeQuery();
        // 处理结果集
        while (rs.next()) {
            System.out.println(rs.getString("userName"));
            System.out.println(rs.getString("name"));
            System.out.println(rs.getInt("age"));
            System.out.println(rs.getDate("birthday"));
        }
    } finally {
        // 关闭连接,释放资源
        if (rs != null) {
            rs.close();
        }
        if (prepareStatement != null) {
            prepareStatement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

}

JDBC连接MYSQL

原文:http://blog.51cto.com/poseidon2011/2343944

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!