zoukankan      html  css  js  c++  java
  • java-通过JDBC操作数据库

    一.加载驱动

    这里我们用Class.forname();来加载驱动,用此语句会提示排除异常。

    Class.forName("com.mysql.jdbc.Driver");

    括号中的内容为Driver.class在引入库中的位置。com.mysql.jdbc是包的名字,Driver是calss的名字。  其他服务器同理,不需要强记这个语句,只需要知道从哪里找就可以。

    二.构建数据库链接

    1 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?characterEncoding=GBK", "root", "");

    1.要连接数据库,需要向java.sql.DriverManager请求并获得Connection对象,该对象就代表一个数据库的连接。

    2.使用DriverManager的getConnectin(String url , String username , String password )方法传入指定的欲连接的数据库的路径、数据库的用户名和 密码来获得。

    也可以这样写

    3.characterEncoding=GBK 后面这部分是调用GBK字符集,能正常显示中文

    1 String url = "jdbc:mysql://localhost:3306/mydb?characterEncoding=GBK"; 
    2         //?characterEncoding=GBK 后面这部分是调用GBK字符集,能正常显示中文
    3 
    4 String user = "root";
    5 String password = "";// 这里密码为空
    6 Connection conn = DriverManager.getConnection(url,user,password);

    4.创建一个statement

       要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3种类型:

           1、执行静态SQL语句。通常通过Statement实例实现。

           2、执行动态SQL语句。通常通过PreparedStatement实例实现。

           3、执行数据库存储过程。通常通过CallableStatement实例实现。

    1 java.sql.Statement state = conn.createStatement();
    2         String sql = "insert into xs values('101','王一','实验中学')";
    3         state.executeUpdate(sql); //增删改
    4         //state.executeQuery(sql) //

    5、执行SQL语句

    Statement接口提供了三种执行SQL语句的方法:executeQuery 、executeUpdate和execute

    1、ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句,返回一个结果集(ResultSet)对象。

    2、int executeUpdate(String sqlString):用于执行INSERT、UPDATE或DELETE语句以及SQL DDL语句,如:CREATE TABLE和DROP TABLE等

    3、execute(sqlString):用于执行返回多个结果集、多个更新计数或二者组合的语句。

    6.关闭数据库

     即断开与服务器的链接  

    conn.close();
  • 相关阅读:
    A20 烧录和启动 log
    图像处理---图像分割技术---基于图像灰度分布的阈值方法一
    H.265---内容总览
    H.265---仿射运动模型和双线性运动模型
    H.265---帧内预测与帧间预测
    linux内核---进程通信---消息队列
    linux内核---嵌入式linux内核的五个子系统
    高并发服务器---nginx---实现负载均衡的几种方式
    高并发服务器---nginx---正向代理和反向代理
    【CV系列】基于形态学梯度的边缘检测
  • 原文地址:https://www.cnblogs.com/kuangwong/p/6245939.html
Copyright © 2011-2022 走看看