恰到好處的喜歡最舒服
懂得分寸的人最迷人
MySQL入門:
http://www.reibang.com/p/56fc082e4549
用Java操作已經(jīng)創(chuàng)建好的數(shù)據(jù)庫 temp_db 的 students 表
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;
//連接數(shù)據(jù)庫方法
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 {
//連接數(shù)據(jù)庫
MySQL m=new MySQL();
m.getConnection();
//插入數(shù)據(jù)
sql=con.prepareStatement("insert into students (name,sex,age) values(?,?,?)");
sql.setString(1, "雪娜");
sql.setString(2, "女");
sql.setString(3, "19");
sql.executeUpdate();
//更新數(shù)據(jù)
sql=con.prepareStatement("update students set age=? where name='阿玲'");
sql.setInt(1, 22);
sql.executeUpdate();
//刪除數(shù)據(jù)
sql=con.prepareStatement("delete from students where name=?");
sql.setString(1, "張三");
sql.executeUpdate();
//查詢數(shù)據(jù)
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);
}
}
}
導(dǎo)入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語句進行預(yù)處理
生產(chǎn)環(huán)境下你一定要考慮使用 PreparedStatement 短蜕,比Statement快