JAVA_JDBC

JDBC概念: 使用JAVA代码操作数据库


-----------------------------

DEMO:

package com.company.jdbc;

import java.sql.*;

public class Main {

// 数据库地址

    static Stringurl ="jdbc:mysql://localhost:3306/mysql";

    static Stringusername ="root";

    static Stringpassword ="12345678";

    public static void main(String[] args)  {

// 1.加载驱动(开发推荐的方式)

        System.out.println("Hello,Java~~~");

        Connection connection =null;

        ResultSet resultSet =null;

        PreparedStatement preparedStatement =null;

        try {

// 2.获取Connection对象 Collection是数据库编程中最重要的一个对象,客户端与数据库所有交互都是通过connection对象完成的

            connection = DriverManager.getConnection(url,username,password);

            // SQL语句

            String sql ="select * from student where name = '张三'";

            // 数据库查询方法,执行SQL语句

            preparedStatement = connection.prepareStatement(sql);

            // 将查询到的结果赋值到ResultSet对象

            resultSet = preparedStatement.executeQuery(sql);

            // 遍历结果

            while (resultSet.next()) {

String name = resultSet.getString("name");

                System.out.println("name:" + name);

            }

}catch (SQLException throwables) {

throwables.printStackTrace();

        }finally {

// 释放资源

            if (resultSet !=null) {

try {

resultSet.close();

                }catch (SQLException throwables) {

throwables.printStackTrace();

                }

}

if (preparedStatement !=null) {

try {

preparedStatement.close();

                }catch (SQLException throwables) {

throwables.printStackTrace();

                }

}

}

}

}

你可能感兴趣的:(JAVA_JDBC)