欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据库连接

程序员文章站 2022-06-11 21:41:41
...
package com.lanou;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class MainClass {
    public static void main(String[] args) {
        //JDBC
        //java内部提供的数据库连接操作的接口
        //可以为多种关系型数据库提供统一的标准
        //


//        数据库连接
        String username = "root";
        String password = "123456";
        String URL="jdbc:mysql://localhost:3306/db0905?useSSL=true";
        String driver="com.mysql.jdbc.Driver";

//        建立数据库连接
        Connection conn=null;
        PreparedStatement stmt=null;
        try {
            //加载数据库驱动
            Class.forName(driver);

            //建立数据库连接对象
            conn = DriverManager.getConnection(URL, username, password);
//        操作数据库
            //sql语句
            String sql="insert into person values(7,'kk',19,'西安')";

            //stmt对象保存sql数据和状态
            stmt = conn.prepareStatement(sql);

            //执行sql语句(返回受影响行数量)
            //增删改
            int result = stmt.executeUpdate();
            System.out.println(result);
            

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                //        关闭连接
                if (stmt != null) {
                    stmt.close();
                }


            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }





    }
}

上一篇: 数据库连接

下一篇: 怎么泡妹纸