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

JDBC编程步骤

时间:2020-02-12 18:58:13      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:cut   dex   code   exce   not   nec   ora   mysq   student   

加载驱动程序:

Class.forName(driverClass)
//加载MySql驱动
Class.forName("com.mysql.jdbc.Driver")
//加载Oracle驱动
Class.forName("oracle.jdbc.driver.OracleDriver")

获得数据库连接:

String url = "jdbc:mysql://localhost:3306/student";
String user = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url, user, password);

创建Statement对象:

Statement statement = connection.createStatement();

例子:

package com.silentteller.test;

import java.sql.*;

public class Test {
    public static void main(String[] args) {
        try {
            //1.加载驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2. 获得数据库连接
            String url = "jdbc:mysql://localhost:3306/student";
            String user = "root";
            String password = "123456";
            Connection connection = DriverManager.getConnection(url, user, password);
            System.out.println(connection);
            //3.操作数据库,实现增删改查
            Statement statement = connection.createStatement();
            String sql = "select * from student";
            ResultSet rs = statement.executeQuery(sql);
            //如果有数据,rs.next()返回true
            while(rs.next()){
                System.out.println(rs.getString("id") + rs.getString("student_id") + rs.getString("name")
                                + rs.getInt("age") + rs.getString("sex") + rs.getString("birthday"));
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

 

JDBC编程步骤

标签:cut   dex   code   exce   not   nec   ora   mysq   student   

原文地址:https://www.cnblogs.com/silentteller/p/12299727.html

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