Java数据库创建于字符编码以及操作

1。数据库连接

private static final String driver = "com.mysql.jdbc.Driver";

private static final String db = "数据库名称";

//注意链接的时候制定数据库字符编码,可以一定程度避免编码插入字符乱码

private static final String url = "jdbc:mysql://localhost:3306/" + db

+ "?useUnicode=true&characterEncoding=utf-8";

private static final String user = "root";

private static final String passwd = "";

//加载数据库驱动

try {

System.out.println(driver);

Class.forName(driver);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

//链接数据库

private boolean isConnection() {

try {

this.connection = DriverManager.getConnection(url, user, passwd);

if (this.connection != null) {

if (this.connection.isClosed()) {

System.out.println("链接失败");

return false;

} else {

System.out.print("链接成功");

return true;

}

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

System.out.print(e.toString());

}

return false;

}

【注意】当链接失败和操作完成的时候注意释放资源 connect和Statement的关闭需要在ResultSet之后

2。数据库创建

//创建的时候注意设置字符集,

CREATE DATABASE `mengwa` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

3。对于一些操作是否成功的判断

  插入操作:判读成功与否不能根据返回结果,而应根据是否捕捉到错误为依据

  删除:同上

  创建:同上

  搜索:可以直接根据返回的RestSet做判断

猜你喜欢

转载自yulongle.iteye.com/blog/2228352
今日推荐