package connect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectDB {
public static void main(String[] args){
Connection con;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/zzh";
String user = "root";
String password = "abc123";
try {
Class.forName(driver);
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
Statement st = con.createStatement();
String sql = "select * from shop";
ResultSet rs = st.executeQuery(sql);
System.out.println("------------------");
System.out.println("?执行结果如下");
System.out.println("------------------");
System.out.println("性别,姓名,密码");
System.out.println("------------------");
String sex = null;
String name = null;
String pass = null;
while(rs.next()){
sex = rs.getString("sex");
name = rs.getString("name");
pass = rs.getString("pass");
System.out.println(sex+"\t"+name+"\t"+pass);
}
rs.close();
con.close();
} catch (ClassNotFoundException e) {
System.out.println("Sorry, can‘t find the Driver!");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
} finally{
System.out.println("数据库数据成功获取");
}
}
}
PS:原则上如果在命令行下访问mysql能正常显示中文,则程序读出来肯定能正常显示中文。
不必再使用name =
new
String(name.getBytes(
"ISO-8859-1"
),
"gb2312"
); 转码了
哈哈