MySQL布爾值,存儲false或true
簡明說,數(shù)據(jù)庫存儲的布爾值是0和1,相當(dāng)于一個字節(jié)的INT型整數(shù)
具體操作
如果是可視化界面,可以直接選擇Boolean,長度設(shè)置為1。其最終顯示的效果等價于TINYINT(1)
所以,zero == false;nonzero == true
MySQL數(shù)據(jù)庫存儲布爾值
在Java編程中,我們經(jīng)常會遇到將boolean值寫入到mysql數(shù)據(jù)庫的情況。但是,mysql數(shù)據(jù)庫是沒有boolean類型的,它的boolean值是用數(shù)字0和1來表示的。
下面,我們用Java演示一下怎樣將boolean值保存到mysql數(shù)據(jù)庫
package database;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.qs.database.DBConnection;
public class JavaMysqlBoolean {
public static void main(String[] args) {
if(DBConnection.conn==null){
DBConnection.openConn();
}
PreparedStatement ps = null;
try {
String sql = "insert into testboolean(name,password,isAdult) values(?,?,?)";
ps = DBConnection.conn.prepareStatement(sql);
ps.setString(1, "lisi");
ps.setString(2, "1");
ps.setBoolean(3, false);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package com.qs.database;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBConnection {
public static Connection conn = null;
public static String driverClass = "";
public static String dbURL = "";
public static String dbUser = "";
public static String dbPwd = "";
static {
loadProperty();
}
// 讀取配置文件
public static boolean loadProperty() {
Properties properties = new Properties();
try {
properties.load(DBConnection.class.getResourceAsStream("db.properties"));
driverClass = properties.getProperty("drivername");
dbURL = properties.getProperty("dburl");
dbUser = properties.getProperty("username");
dbPwd = properties.getProperty("password");
} catch (IOException e) {
System.out.println("讀取配置文件失敗");
e.printStackTrace();
return false;
}
return true;
}
public static void openConn() {
// 加載驅(qū)動類
try {
Class.forName(driverClass).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
System.out.println("驅(qū)動類沒有找到,加載失敗");
return;
}
// 獲得與指定數(shù)據(jù)庫的連接
try {
conn = DriverManager.getConnection(dbURL, dbUser, dbPwd);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void closeConn() {
if (conn != null) {
try {
conn.close();
conn = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
屬性文件db.properties
drivername=org.gjt.mm.mysql.Driver
dburl=jdbc:mysql://localhost:3306/mydatabase?useUnicode=truecharacterEncoding=utf-8
username=root
password=root
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- JDBC對MySQL數(shù)據(jù)庫布爾字段的操作方法
- mybatis 連接mysql數(shù)據(jù)庫 tinyint 為boolean類型詳解
- Mysql NULL導(dǎo)致的神坑