jdbc操作数据库

 安装mysql数据库,下载mybatis-3.2.7.jar包


一、创建数据库

package com.jdbc;

import java.sql.*;
//创建数据库
public class CreateDatabase {
    static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
    static final String DB_URL="jdbc:mysql://localhost/";

    static final String USER="root";
    static final String PASS="zhz0514";

    public static void main(String[] args){
        Connection conn = null;
        Statement stmt = null;
        try{
            Class.forName ("com.mysql.jdbc.Driver");

            System.out.println ("Connecting to database...");
            conn = DriverManager.getConnection (DB_URL,USER,PASS);

            System.out.println ("Creating database...");
            stmt = conn.createStatement ();

            String sql = "CREATE DATABASE jdbc_db";
            stmt.executeUpdate (sql);
            System.out.println ("Database created successsfully...");
        }catch (SQLException se){
            se.printStackTrace ();
        }catch (Exception e){
            e.printStackTrace ();
        }finally {
            try{
                if (stmt!=null)
                    stmt.close ();
            }catch (SQLException se2){
                try{
                    if (conn!=null)
                        conn.close ();
                }catch (SQLException se){
                    se.printStackTrace ();
                }
            }
        }
        System.out.println ("Goodbye");
    }
}

二、创建表

package com.jdbc;

import org.omg.Messaging.SYNC_WITH_TRANSPORT;

import java.sql.*;
//创建表
public class CreateTable {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/jdbc_db";

    static final String USER = "root";
    static final String PASS = "zhz0514";

    public static void main(String[] args){
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName ("com.mysql.jdbc.Driver");

            System.out.println ("Connecting to a selected database...");
            conn = DriverManager.getConnection (DB_URL,USER,PASS);
            System.out.println ("Connected database successfully...");

            System.out.println ("Creating table in given database...");
            stmt = conn.createStatement ();

            String sql = "CREATE TABLE student"+
                         "(id INTEGER not NULL,"+
                         "first VARCHAR(255),"+
                         "last VARCHAR(255),"+
                         "age INTEGER,"+
                         "PRIMARY KEY(id))";
            stmt.executeUpdate (sql);
            System.out.println ("Created table in given database...");
        }catch (SQLException se){
            se.printStackTrace ();
        }catch (Exception e){
            e.printStackTrace ();
        }finally {
            try {
                if (stmt!=null)
                    conn.close ();
            }catch (SQLException se){
            }
            try {
                if (conn!=null)
                    conn.close ();
            }catch (SQLException se){
                se.printStackTrace ();
            }
        }
        System.out.println ("Goodbye!");
    }
}

三、插入数据

import java.sql.*;
//插入数据
public class InsertRecords {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/jdbc_db";

    static final String USER = "root";
    static final String PASS = "zhz0514";

    public static void main(String[] args){
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");

            //STEP 3: Open a connection
            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connected database successfully...");

            //STEP 4: Execute a query
            System.out.println("Inserting records into the table...");
            stmt = conn.createStatement();

            String sql = "INSERT INTO student " +
                    "VALUES (100, 'C++', 'Li', 18)";
            stmt.executeUpdate(sql);
            sql = "INSERT INTO student " +
                    "VALUES (101, 'Python', 'Py', 25)";
            stmt.executeUpdate(sql);
            sql = "INSERT INTO student " +
                    "VALUES (102, 'Ruby', 'Ru', 30)";
            stmt.executeUpdate(sql);
            sql = "INSERT INTO student " +
                    "VALUES(103, 'Java', 'Ja', 28)";
            stmt.executeUpdate(sql);
            System.out.println("Inserted records into the table...");
        }catch (SQLException se){
            se.printStackTrace ();
        }catch (Exception e){
            e.printStackTrace ();
        }finally {
            try {
                if (stmt!=null)
                    conn.close ();
            }catch (SQLException se){
        }
        try {
                if (conn!=null)
                    conn.close ();
        }catch (SQLException se){
                se.printStackTrace ();
        }
        }
        System.out.println ("Goodbye!");
    }
}

四、选择数据库

package com.jdbc;

import java.sql.*;
//选择数据库
public class SelectDatabase {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/jdbc_db";

    static final String USER = "root";
    static final String PASS = "zhz0514";

    public static void main (String[] args){
        Connection conn = null;
        try{
            Class.forName ("com.mysql.jdbc.Driver");

            System.out.println ("Connecting to a selected database...");
            conn = DriverManager.getConnection (DB_URL,USER,PASS);
            System.out.println ("Connected database successfully...");
        }catch (SQLException se){
            se.printStackTrace ();
        }catch (Exception e){
            e.printStackTrace ();
        }finally {
            try{
                if (conn!=null)
                    conn.close ();
            }catch (SQLException se){
                se.printStackTrace ();
            }
        }
        System.out.println ("Goodbye!");
    }
}

五、查询数据

package com.jdbc;

import java.sql.*;
//查询数据
public class SelectRecords {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/jdbc_db";

    static final String USER = "root";
    static final String PASS = "zhz0514";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            Class.forName("com.mysql.jdbc.Driver");

            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connected database successfully...");

            System.out.println("Creating statement...");
            stmt = conn.createStatement();

            String sql = "SELECT id, first, last, age FROM student";
            ResultSet rs = stmt.executeQuery(sql);
            while(rs.next()){
                int id  = rs.getInt("id");
                int age = rs.getInt("age");
                String first = rs.getString("first");
                String last = rs.getString("last");

                System.out.print("ID: " + id);
                System.out.print(", Age: " + age);
                System.out.print(", First: " + first);
                System.out.println(", Last: " + last);
            }
            rs.close();
        }catch(SQLException se){
            se.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(stmt!=null)
                    conn.close();
            }catch(SQLException se){
            }
            try{
                if(conn!=null)
                    conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

六、更新数据

package com.jdbc;

import java.sql.*;
//更新数据
public class UpdateRecords {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/jdbc_db";

    static final String USER = "root";
    static final String PASS = "zhz0514";

    public static void main(String[] args){
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName ("com.mysql.jdbc.Driver");

            System.out.println ("Connecting to a selected datavase...");
            conn = DriverManager.getConnection (DB_URL,USER,PASS);
            System.out.println ("Connected database successfully...");

            System.out.println ("Creating statment");
            stmt = conn.createStatement ();
            stmt = conn.createStatement();
            String sql = "UPDATE student " +
                    "SET age = 22 WHERE id in (100, 101)";
            stmt.executeUpdate(sql);

            sql = "SELECT id, first, last, age FROM student";
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next ()){
                int id = rs.getInt ("id");
                int age = rs.getInt ("age");
                String first = rs.getString ("first");
                String last = rs.getString ("last");

                System.out.print ("ID:"+id);
                System.out.print(", Age: " + age);
                System.out.print(", First: " + first);
                System.out.println(", Last: " + last);
            }
            rs.close ();
        }catch (SQLException se){
            se.printStackTrace ();
        }catch (Exception e){
            e.printStackTrace ();
        }finally {
            try {
                if (stmt!=null)
                    conn.close ();
            }catch (SQLException se){
                se.printStackTrace ();
        }
        }
        System.out.println ("Goodbye!");
        }
        }

七、删除数据

package com.jdbc;

import java.sql.*;
//删除数据
public class DeleteRecords {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/jdbc_db";

    static final String USER = "root";
    static final String PASS = "zhz0514";

    public static void main(String[] args){
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");

            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connected database successfully...");

            System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql = "DELETE FROM student " +
                    "WHERE id = 101";
            stmt.executeUpdate(sql);

            sql = "SELECT id, first, last, age FROM student";
            ResultSet rs = stmt.executeQuery(sql);

            while(rs.next()){
                //Retrieve by column name
                int id  = rs.getInt("id");
                int age = rs.getInt("age");
                String first = rs.getString("first");
                String last = rs.getString("last");

                //Display values
                System.out.print("ID: " + id);
                System.out.print(", Age: " + age);
                System.out.print(", First: " + first);
                System.out.println(", Last: " + last);
            }
            rs.close ();
        }catch (SQLException se){
            se.printStackTrace ();
        }catch (Exception e){
            e.printStackTrace ();
        }finally {
            try {
                if (stmt!=null)
                    conn.close ();
            }catch (SQLException se){
                se.printStackTrace ();
            }
        }
        System.out.println ("Goodbye!");
    }
}

八、删除数据库

package com.jdbc;

import java.sql.*;
//删除数据库
public class DropDatabase {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/";

    static final String USER = "root";
    static final String PASS = "zhz0514";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try{
            Class.forName("com.mysql.jdbc.Driver");

            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Connected database successfully...");

            System.out.println("Deleting database...");
            stmt = conn.createStatement();

            String sql = "DROP DATABASE jdbc_db";
            stmt.executeUpdate(sql);
            System.out.println("Database deleted successfully...");
        }catch(SQLException se){
            se.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(stmt!=null)
                    conn.close();
            }catch(SQLException se){
            }
            try{
                if(conn!=null)
                    conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JDBC(Java Database Connectivity)是Java语言操作数据库的标准接口,通过它可以实现对关系型数据库的访问。 JDBC操作数据库的步骤如下: 1. 加载数据库驱动程序:首先需要加载特定数据库的驱动程序,例如MySQL、Oracle等。可以使用Class.forName()方法加载驱动程序。 2. 建立数据库连接:使用DriverManager.getConnection()方法创建一个数据库连接对象。需要传入数据库URL、用户名和密码等参数。 3. 创建Statement对象:创建一个Statement对象,用于向数据库发送SQL语句。 4. 执行SQL语句:使用Statement对象的execute()、executeUpdate()和executeQuery()方法执行SQL语句。 5. 处理结果集:如果执行的SQL语句返回结果集,需要使用ResultSet对象来处理结果集。ResultSet对象包含了查询结果的所有行和列。 6. 关闭数据库连接:使用Connection对象的close()方法关闭数据库连接。 以下是一个简单的JDBC操作数据库的示例代码: ```java import java.sql.*; public class JdbcDemo { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8"; String username = "root"; String password = "123456"; try { // 加载MySQL驱动程序 Class.forName("com.mysql.jdbc.Driver"); // 建立数据库连接 Connection conn = DriverManager.getConnection(url, username, password); // 创建Statement对象 Statement stmt = conn.createStatement(); // 执行SQL语句 ResultSet rs = stmt.executeQuery("SELECT * FROM user"); // 处理结果集 while (rs.next()) { System.out.println(rs.getString("username")); } // 关闭数据库连接 conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值