zoukankan      html  css  js  c++  java
  • Java数据库编程(JDBC)

    一.使用Java对数据库的操作步骤:

      1.根据应用程序的数据库类型,加载相应的驱动;

      2.连接到数据库,得到Connection对象;

      3.通过Connection创建Statement对象;

      4.使用Statement对象提交SQL语句;

      5.操作结果集

      6.回收数据库资源

      7.关闭连接

    package com.lovo.jdbc;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    public class JdbcTestDML {
    
        public static void main(String[] args) {
            //数据库操作步骤:
            //1、加载驱动——告诉驱动管理器我们将使用哪一个数据库的驱动包
            try {
                //url——统一资源定位符----样式:  协议://ip地址:端口号/服务
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            //2、操作JDBC API完成数据库动作
            //①、获取连接
            Connection con = null;
            try {
                //?useSSL=false——是指不显示安全警告,?useUnicode=true&characterEncoding=utf8——出现乱码时改成自己一致的编码如utf-8d的
                con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test134?useSSL=false", "root", "13405");
                //②-1、书写SQL语句------字符串拼接、
                //增加
                //String sql="INSERT INTO t_class (f_classname,f_teacher) VALUES ('j22','弯弯')";
                //更改
                String sql="UPDATE t_class SET f_classname ='j66',f_teacher='极低' WHERE pk_classsid =4";
                //②-2、获取语句对象-----statement对像
                Statement state =con.createStatement();
                //②-3、执行语句对象------所有的DML语句,全部执行executeUpdate()方法
                int row=state.executeUpdate(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                //③、关闭连接
                if(con!=null){
                    try {
                        con.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    
    }

     上面这个例子用的是DML语句只有增删改,因此没有结果集的返回,当使用DQL语句做查询时,就会有结果集的出现和使用。

  • 相关阅读:
    Lerning Entity Framework 6 ------ Defining Relationships
    Lerning Entity Framework 6 ------ Defining the Database Structure
    Lerning Entity Framework 6 ------ Introduction to TPH
    Lerning Entity Framework 6 ------ Introduction to TPT
    Lerning Entity Framework 6 ------ Using a commandInterceptor
    Lerning Entity Framework 6 ------ A demo of using Entity framework with MySql
    C#是否该支持“try/catch/else”语法
    Hadoop学习之旅三:MapReduce
    CLR via C# 摘要二:IL速记
    Java 制表符 " "
  • 原文地址:https://www.cnblogs.com/qq1083735206/p/6261990.html
Copyright © 2011-2022 走看看