本文主要向大家讲述的是JDBC 连接MySQL数据库的实际操作过程与在其实际操作中一些值得我们大家注意的事项的描述。
以下的文章主要介绍的是JDBC 连接MySQL数据库的实际操作过程以及在其实际操作中期实际应用代码的描述,以下就是JDBC 连接MySQL数据库的具体方案的描述,希望在你今后的学习中会有所帮助。
- publicclassMySQLJdbc{
- publicStringdriverName="com.MySQL.jdbc.Driver";
- publicStringurl="jdbc:MySQL://localhost:3306/oa";
- publicStringuserName="root";
- publicStringuserPwd="me";
- /**
- *Apr19,200912:49:55PM
- *
- *@paramargs
- */
- publicstaticvoidmain(String[]args){
- MySQLJdbcmy=newMySQLJdbc();
- my.read();
- }
- publicvoidread(){
- StringqueryString="selectuserName,realNamefromuser";
- Connectionconn=null;
- Statementst=null;
- ResultSetrs=null;
- try{
加载驱动
- Class.forName(driverName);
创建连接MySQL数据库
- conn=DriverManager.getConnection(url,userName,userPwd);
创建Statement
- st=conn.createStatement();
执行sql语句,得到查询结果
- rs=st.executeQuery(queryString);
输出查询结果
- while(rs.next()){
- System.out.println("userName:"+rs.getString("userName")
- +"realName:"+rs.getString("realName"));
- }
关闭资源
- rs.close();
- st.close();
- conn.close();
- }catch(Exceptionex){
输出错误信息
- ex.printStackTrace();
- }finally{
finally子句总是会执行(就算发生错误),这样可以保证资源的绝对关闭
- try{
- if(rs!=null)
- rs.close();
- }catch(SQLExceptione){
- e.printStackTrace();
- }
- try{
- if(st!=null)
- st.close();
- }catch(SQLExceptione){
- e.printStackTrace();
- }
- try{
- if(conn!=null)
- conn.close();
- }catch(SQLExceptione){
- e.printStackTrace();
- }
- }
- }
- }
以上的相关内容就是对JDBC 连接MySQL数据库的介绍,望你能有所收获。
【编辑推荐】
- Nagios mysql备份的详细脚本代码
- CentOS系统找回mysql登录密码
- CentOS系统5编译安装mysql-4.1.22
- CentOS系统安装MySQL支持远程连接的方法
- Ubuntu MySQL设置同步服务器
转载请说明出处
知优网 » JDBC 连接MySQL数据库实战演示(jdbc连接MySQL数据库步骤)
知优网 » JDBC 连接MySQL数据库实战演示(jdbc连接MySQL数据库步骤)