MySQL布尔值,存储false或true
简明说,数据库存储的布尔值是0和1,相当于一个字节的INT型整数
具体操作
如果是可视化界面,可以直接选择Boolean,长度设置为1。其最终显示的效果等价于TINYINT(1)
所以,zero == false;nonzero == true
MySQL数据库存储布尔值
在Java编程中,我们经常会遇到将boolean值写入到mysql数据库的情况。但是,mysql数据库是没有boolean类型的,它的boolean值是用数字0和1来表示的。
下面,我们用Java演示一下怎样将boolean值保存到mysql数据库
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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();
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
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() {
// 加载驱动类
try {
Class.forName(driverClass).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
System.out.println( "驱动类没有找到,加载失败" );
return ;
}
// 获得与指定数据库的连接
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
1
2
3
4
|
drivername=org.gjt.mm.mysql.Driver
dburl=jdbc:mysql: //localhost:3306/mydatabase?useUnicode=true&characterEncoding=utf-8
username=root
password=root
|
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/SmartLoveyu/article/details/104594598