數據庫的創建與連接
連接數據庫,首先要創建數據庫和表
創建數據庫的SQL語句如下:CALZZ爲數據庫的名稱CREATE DATABASE CALZZ
創建表的SQL語句:create table 表名(字段名,字段類型(字段長度))
student爲表的名字(屬性 主鍵(一個Table中只能有一個主鍵,使用這個值唯一標示一條數據),如:id。屬性名字,屬性類型(長度)是否允許爲空 是否爲主鍵PRIMARY KEY,是否自增長AUTO_INCREMENT,是否忽略大小寫,SQL語句默認爲忽略大小寫)(允許擁有別的表中的主鍵,即外鍵)CREATE TABLE student (id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,name varchar(20) NOT NULL BINARY,sex int(1) BINARY,age int (3) BINARY)
SQL語句的增、刪、改、查。
增insert語句:
insert into 表名(字段名1,字段名2,···) value (屬性值1,屬性值2,···)
例如:insert into student(name,sex,age)values(‘張三’,1,18)刪delect語句:
delect from 表名 where 條件表達式
例如:delete from student where id=8改update語句
update 表名 set 字段名=新的字段值 where 條件表達式
例如:update student set name=’王五’ where id=7查select語句
select 所選字段列表 from 數據表明 where 條件表達式 Group by 字段名 having 條件表達式(指定分組的條件) order by 字段名[asc|desc]
例如:SELECT * FROM USER WHERE name=’LISI’ and password=’123456’
連接數據庫的時候,需要將SQL的jar包導入
數據庫名,用戶名,密碼
連接數據驅動
**
* 建立於數據庫的連接
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.xml.transform.Result;
import jie0805.Consumer;
public class MySQLTest {
public static void main(String[] args) {
//鏈接數據庫驅動
String driver="com.mysql.jdbc.Driver";
//URL指向要訪問的數據庫名
String url="jdbc:mysql://localhost:3306/calzz";
//MySQL配置使得用戶名
String user="root";
//Java連接MySQL時配置的密碼
String password="2012163";
try {
Class.forName(driver);//加載驅動
//與數據庫建立連接
//通過DriverManager的靜態方法getConnection創建連接對象
Connection conn=DriverManager.getConnection(url,user,password);
if (!conn.isClosed()) {
//數據庫操作類
//向數據庫發送一個SQL語句,使用一個statement接口聲明一個SQL語句對象
//並通過剛創建的連接數據庫對象的createStatement創建這個SQL對象
Statement state=conn.createStatement();
String sql="insert into student(name,sex,age)values('張三',1,18)";
// state.execute(sql);
String update="update student set name='王五' where id=7";
state.execute(update);
String delete="delete from student where id=8";
//execute執行靜態的SQL語句,返回多個結果集
//executeQuery執行靜態的SQL語句,返回單個結果集ResultSet對象
state.execute(delete);
String select="select * from student";
// state.executeQuery(select);
//用來暫時存放數據庫查詢操作的所獲得結果集
ResultSet set=state.executeQuery(select);
//first將指針或光標一道當前記錄的第一行,last將指針或光標一道當前記錄的最後一行
set.first();
while (!set.isLast()) {
System.out.println(set.getString("name"));
//將指針或光標一道當前記錄的下一行
//getRow查看當前行的索引號
set.next();
}
System.out.println("執行成功");
}else{
System.out.println("請打開數據庫");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
單例模式,只創建一個對象,節省空間內存
具體步驟:、單例設計模式
1、私有構造器
2、靜態公開的方法,方法加線程鎖
3、私有靜態的屬性
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLManager {
public Connection conn;
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public Statement state;
public Statement getState() {
return state;
}
public void setState(Statement state) {
this.state = state;
}
//單例設計模式
private static SQLManager manager;
public static synchronized SQLManager newInstabce(){
if (manager==null) {
manager=new SQLManager();
}
return manager;
}
private SQLManager() {
//鏈接數據庫驅動
String driver="com.mysql.jdbc.Driver";
//URL指向要訪問的數據庫名
String url="jdbc:mysql://localhost:3306/calzz";
//MySQL配置使得用戶名
String user="root";
//Java連接MySQL時配置的密碼
String password="2012163";
try {
Class.forName(driver);//加載驅動
//與數據庫建立連接
conn=DriverManager.getConnection(url,user,password);
if (!conn.isClosed()) {
//數據庫操作類
state=conn.createStatement();
String creatTable="CREATE TABLE if not exists user (id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,name varchar(20) BINARY NOT NULL,password int(6) NOT NULL )";
state.execute(creatTable);
System.out.println("執行成功");
}else{
System.out.println("請打開數據庫");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Test類
public class SQLTest {
public static void main(String[] args) {
SQLManager manaer1=SQLManager.newInstabce();
SQLManager manaer2=SQLManager.newInstabce();
SQLManager manaer3=SQLManager.newInstabce();
System.out.println(manaer1+"\n"+manaer2+"\n"+manaer3);
}
}
執行的結果對象只有一個:
執行成功
jie0810.SQLManager@8cf4c6
jie0810.SQLManager@8cf4c6
jie0810.SQLManager@8cf4c6
客戶端直接連接數據庫
/**
*主要代碼,可以寫在按鈕事件響應裏
*/
Statement statement=SQLManager.newInstabce().getState();
String name=textFieldName.getText();
String password=textField_1Password.getText();
// boolean isSignIn=SQLOperate.isSignIn(name, password);
// if (isSignIn) {
// System.out.println("登陸成功");
// }else{
// System.out.println("登陸失敗");
// }
String login="select * from user where BINARY name='"+name+"'and password='"+password+"'";
try {
ResultSet set=statement.executeQuery(login);
System.out.println(set.last());
int num=set.getRow();
System.out.println(num);
if (num>0) {
System.out.println("登陸成功");
textFieldName.setText("");
textField_1Password.setText("");
}else{
System.out.println("賬號密碼不正確,請重新登錄");
textFieldName.setText("");
textField_1Password.setText("");
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String name=textFieldName.getText();
String regexname="\\w{1,20}";
String password=textField_1Password.getText();
String regexpassword="\\w{1,6}";
//MVC設計模式,將界面和數據操作分開
boolean isSignIn=SQLOperate.isSignIn(name, password);
if (isSignIn) {
System.out.println("登陸成功");
}else{
System.out.println("登陸失敗");
}
//防止密碼後加'or 1='登錄,preparedStatement進行預編譯
if (name.matches(regexname) && password.matches(regexpassword)) {
System.out.println("賬戶與密碼格式正確");
Statement state = SQLManager.newInstabce().getState();
Connection coon=SQLManager.newInstabce().getConn();
try {
if (!coon.isClosed()) {
PreparedStatement preparedStatement=coon.prepareStatement("select * from student where name=? and password=?");
preparedStatement.setString(1, name);
preparedStatement.setString(1, password);
ResultSet set=preparedStatement.executeQuery();
set.last();
int num=set.getRow();
System.out.println("查詢的結果"+num);
}
} catch (SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String select = "select count(*) from student where name='" + name + "'";
try {
ResultSet set = state.executeQuery(select);
// set.first();
// int num1 = set.getInt(1);
set.last();
int num1=set.getRow();
if (num1 > 0) {
System.out.println("該用戶已存在");
} else {
String register = "insert into user(name,password)values('" + name + "','" + password
+ "')";
state.execute(register);
System.out.println("註冊成功");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}else{
System.out.println("賬戶與密碼格式不正確");
}