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

JDBC连接MYSQL

时间:2019-01-17 23:43:21      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:row   rman   com   void   user   result   HERE   oid   处理   

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

标签:row   rman   com   void   user   result   HERE   oid   处理   

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

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