mysql的check約束在當前mysql版本中依然是個擺設(mysql版本5.7.9)
那麼要怎麼取現救國,實現類似check約束的功能呢?
解決方案:
1.使用觸發器,來完成類似check的約束驗證
2.使用set或enum方式來完成字符串的值範圍check約束
//1.set的效果
mysql> create table test(
-> id bigint primary key auto_increment,
-> paymethod set('貨到付款','支付寶付款')
-> );
Query OK, 0 rows affected (0.02 sec)
mysql> insert into test(paymethod) values('貨到付款');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test(paymethod) values('貨到付');
ERROR 1265 (01000): Data truncated for column 'paymethod' at row 1
在java程序中可以讀取相關信息:
package com.xie.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test {
public static void main(String[] args){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection ct=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/shop","root","centre");
PreparedStatement ps=ct.prepareStatement("select * from test");
ResultSet rs=ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getLong(1));
System.out.println(rs.getString(2));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}運行結果:
1
貨到付款
//2.enum的效果:
mysql> create table test(
-> id bigint primary key auto_increment,
-> paymethod enum('貨到付款','支付寶付款')
-> );
Query OK, 0 rows affected (0.00 sec)
mysql> insert into test(paymethod) values('貨到付款');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test(paymethod) values('貨到付');
ERROR 1265 (01000): Data truncated for column 'paymethod' at row 1
測試java代碼如上:
測試結果:
1
貨到付款