Java 数据库

2018-04-25  本文已影响0人  一杯清凉的水

恰到好处的喜欢最舒服
懂得分寸的人最迷人

Java 数据库

MySQL入门:
https://www.jianshu.com/p/56fc082e4549

用Java操作已经创建好的数据库 temp_db 的 students 表

MySQL.png
package c2;

import java.sql.*;

public class MySQL {
    
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/temp_db?useSSL=false";
 
    static final String USER = "root";
    static final String PASS = "root";

    static Connection con;
    static PreparedStatement sql;
    static ResultSet res;
    
    //连接数据库方法
    public Connection getConnection() throws ClassNotFoundException, SQLException {
        
        Class.forName(JDBC_DRIVER);
        con = DriverManager.getConnection(DB_URL,USER,PASS);
        
        return con;
    }
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        
        //连接数据库
        MySQL m=new MySQL();
        m.getConnection();
        
        //插入数据
        sql=con.prepareStatement("insert into students (name,sex,age) values(?,?,?)");
        sql.setString(1, "雪娜");
        sql.setString(2, "女");
        sql.setString(3, "19");
        sql.executeUpdate();
        
        //更新数据
        sql=con.prepareStatement("update students set age=? where name='阿玲'");
        sql.setInt(1, 22);
        sql.executeUpdate();
        
        //删除数据
        sql=con.prepareStatement("delete from students where name=?");
        sql.setString(1, "张三");
        sql.executeUpdate();
        
        //查询数据
        sql=con.prepareStatement("select *from students");
        res=sql.executeQuery();
        
        while(res.next()) {
    
            int id=res.getInt("id");
            String name=res.getString("name");
            String sex=res.getString("sex");
            int age=res.getInt("age");
            Date date=res.getDate("dates");
            Time time=res.getTime("dates");

            System.out.print("id:" + id);
            System.out.print(" name:" + name);
            System.out.print(" sex:" + sex);
            System.out.print(" age:" + age);
            System.out.println(" date:" + date);
            System.out.println(" time:" + time);
        }
    }
}

运行结果:

image.png
导入jar包:

右键java项目>Properties>Java Build Path>Libraries>Add External JARs

如果报错:

Wed Apr 25 23:49:55 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. ...

在 url 最后加上 ?useSSL=false 即可,eg:

static final String DB_URL = "jdbc:mysql://localhost:3306/temp_db?useSSL=false";
PreparedStatement 方法对sql语句进行预处理

生产环境下你一定要考虑使用 PreparedStatement ,比Statement快

上一篇下一篇

猜你喜欢

热点阅读