首页 > 数据库技术 > 详细

java中连接数据库的步骤

时间:2019-12-23 23:49:47      阅读:99      评论:0      收藏:0      [点我收藏+]

JDBC(连接数据库)

简单连接数据库的步骤:

1、将mysql的jdbc驱动加载到内存中

指定需要连接的数据库地址、用户名和密码;

2、获取连接;

3、通过连接创建Statement对象;

4、执行数据库(DML);

jdbc 中增、删、改都是executeUpdate方法

5、关闭数据库;

 


代码详情如下:

package com.yj.test;
?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
?
public class Test {
public static void main(String[] args) {
//  1、将mysql的jdbc驱动加载到内存中
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    
       //指定需要连接的数据库地址,用户和密码
    String url = "jdbc:mysql://127.0.0.1:3306/bus";
    String user = "root";
    String password = "123456";
    
      Connection  conn = null;
      Statement stmt = null;
      
      
      try {
//    2、获取链接
        conn = DriverManager.getConnection(url,user,password);
//    3、通过连接创建statement对象
        stmt = conn.createStatement();
        
//    4、执行数据库语句
        //jdbc中增、删、改都是executeUpdate方法
        //这个方法会返回一个int类型的值
        //对应就是几行数据受影响
        //插入(增加)语句
        int n = stmt.executeUpdate("insert into t_user(username,userpwd,tel,address,sex)values(‘333‘,‘222‘,‘222‘,‘1211111112‘,‘男‘)");
        //删除语句
        //int n = stmt.executeUpdate("delete from t_user where sex=‘男‘");
        
        //修改语句
        //int n = stmt.executeUpdate("update t_user set sex=‘女‘,address=‘绵阳‘,tel=‘13888888888‘ where u_pk_id=1");
        System.out.println(n + "个受影响");
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
//     5、关闭数据库
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn !=null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
?
 }
}
?

 

 

java中连接数据库的步骤

原文:https://www.cnblogs.com/suger-4/p/12088875.html

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