以下是我编写的向MySql数据库插入记录的程序,但是插入成功后数据库中的中文字符都变成了?号!//PreparedStatementTest源程序
import java.sql.*;public class PreparedStatementTest { public static void main(String[] args) {
Connection con = null;
PreparedStatement stmt = null;
String [] cof_name = { "中国大陆咖啡", "中国香港咖啡" };
int [] sup_id = { 25, 60 };
float [] price = { 9.00f, 12.56f };
int [] sales = { 0, 0 };
int [] total = { 0, 0 };
try {
Class.forName( "com.mysql.jdbc.Driver" );
con = DriverManager.getConnection(
"jdbc:mysql://localhost/coffeebreak", "root", "" );
stmt = con.prepareStatement( "INSERT INTO COFFEES " +
"VALUES( ?, ?, ?, ?, ? )" );
for( int i = 0; i < cof_name.length; i++ ) {
stmt.setString( 1, cof_name[i] );
stmt.setInt( 2, sup_id[i] );
stmt.setFloat( 3, price[i] );
stmt.setInt( 4, sales[i] );
stmt.setInt( 5, total[i] );
stmt.executeUpdate();
}
con.close();
stmt.close();
}
catch( ClassNotFoundException e ) {
e.getMessage();
}
catch( SQLException e ) {
e.getMessage();
}
}
}
下面是用"SELECT * FROM COFFEES"查询的结果其中?号为中文字符:
Colombian 101 7.99 75 0
French_Roast 49 8.99 0 0
Espresso 150 9.99 0 0
Colombian_Decaf 101 8.99 0 0
French_Roast_Decaf 49 9.99 0 0
?????? 25 9.0 0 0
?????? 60 12.56 0 0
import java.sql.*;public class PreparedStatementTest { public static void main(String[] args) {
Connection con = null;
PreparedStatement stmt = null;
String [] cof_name = { "中国大陆咖啡", "中国香港咖啡" };
int [] sup_id = { 25, 60 };
float [] price = { 9.00f, 12.56f };
int [] sales = { 0, 0 };
int [] total = { 0, 0 };
try {
Class.forName( "com.mysql.jdbc.Driver" );
con = DriverManager.getConnection(
"jdbc:mysql://localhost/coffeebreak", "root", "" );
stmt = con.prepareStatement( "INSERT INTO COFFEES " +
"VALUES( ?, ?, ?, ?, ? )" );
for( int i = 0; i < cof_name.length; i++ ) {
stmt.setString( 1, cof_name[i] );
stmt.setInt( 2, sup_id[i] );
stmt.setFloat( 3, price[i] );
stmt.setInt( 4, sales[i] );
stmt.setInt( 5, total[i] );
stmt.executeUpdate();
}
con.close();
stmt.close();
}
catch( ClassNotFoundException e ) {
e.getMessage();
}
catch( SQLException e ) {
e.getMessage();
}
}
}
下面是用"SELECT * FROM COFFEES"查询的结果其中?号为中文字符:
Colombian 101 7.99 75 0
French_Roast 49 8.99 0 0
Espresso 150 9.99 0 0
Colombian_Decaf 101 8.99 0 0
French_Roast_Decaf 49 9.99 0 0
?????? 25 9.0 0 0
?????? 60 12.56 0 0
jdbc:mysql://localhost/coffeebreak?characterEncoding=gbk&useUnicode=true
要显示mysql的中文需要下面几条命令的
SET character_set_client = gb2312;
SET character_set_connection = gb2312;
SET character_set_results = gb2312;
SET collation_connection = gb2312_bin;
这是在dos下的,
页面上就要自己做个包了
con = DriverManager.getConnection("jdbc:mysql://localhost/coffeebreak", "root", "" );
-------------------------------------画线部分改为
"jdbc:mysql://localhost/coffeebreak?useUnicode=true&characterEncoding=GB2312"
jdbc:mysql://localhost/coffeebreak?characterEncoding=gbk&useUnicode=true