对数据库进行查询、添加、删除、修改等操作时,都必须通过JDBC建立应用程序与数据库的连接。
连接数据库时,一般需要指定数据库读写的编码,这里采用“UTF-8”编码。实现注册驱动并建立数据库的连接的关键代码段如下:
String driveName=“com.mysql.jdbc.Driver”;
String userName ="root";
String userPwd="123456"
String dbName ="students";
String url1="jdbc:mysql://localhost:3306/"+dbName;
String url2="?user="+userName+"&password="+userPwd;
String url3="&useUnicode=true&characterEncoding=UTF-8";
String url=url1+url2+url3;
Class.forName(driveName);
Connection conn=DriverManager.getConnection(url);