本文主要向大家讲述的是JDBC 连接MySQL数据库的实际操作过程与在其实际操作中一些值得我们大家注意的事项的描述。

以下的文章主要介绍的是JDBC 连接MySQL数据库的实际操作过程以及在其实际操作中期实际应用代码的描述,以下就是JDBC 连接MySQL数据库的具体方案的描述,希望在你今后的学习中会有所帮助。

JDBC 连接MySQL数据库实战演示(jdbc连接MySQL数据库步骤)  连接MySQL数据库 第1张

  1. publicclassMySQLJdbc{
  2. publicStringdriverName="com.MySQL.jdbc.Driver";
  3. publicStringurl="jdbc:MySQL://localhost:3306/oa";
  4. publicStringuserName="root";
  5. publicStringuserPwd="me";
  6. /**
  7. *Apr19,200912:49:55PM
  8. *
  9. *@paramargs
  10. */
  11. publicstaticvoidmain(String[]args){
  12. MySQLJdbcmy=newMySQLJdbc();
  13. my.read();
  14. }
  15. publicvoidread(){
  16. StringqueryString="selectuserName,realNamefromuser";
  17. Connectionconn=null;
  18. Statementst=null;
  19. ResultSetrs=null;
  20. try{

加载驱动

  1. Class.forName(driverName);

创建连接MySQL数据库

  1. conn=DriverManager.getConnection(url,userName,userPwd);


创建Statement

  1. st=conn.createStatement();


执行sql语句,得到查询结果

  1. rs=st.executeQuery(queryString);

输出查询结果

  1. while(rs.next()){
  2. System.out.println("userName:"+rs.getString("userName")
  3. +"realName:"+rs.getString("realName"));
  4. }

关闭资源

  1. rs.close();
  2. st.close();
  3. conn.close();
  4. }catch(Exceptionex){

输出错误信息

  1. ex.printStackTrace();
  2. }finally{

finally子句总是会执行(就算发生错误),这样可以保证资源的绝对关闭

  1. try{
  2. if(rs!=null)
  3. rs.close();
  4. }catch(SQLExceptione){
  5. e.printStackTrace();
  6. }
  7. try{
  8. if(st!=null)
  9. st.close();
  10. }catch(SQLExceptione){
  11. e.printStackTrace();
  12. }
  13. try{
  14. if(conn!=null)
  15. conn.close();
  16. }catch(SQLExceptione){
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21. }

以上的相关内容就是对JDBC 连接MySQL数据库的介绍,望你能有所收获。

【编辑推荐】

  1. Nagios mysql备份的详细脚本代码
  2. CentOS系统找回mysql登录密码
  3. CentOS系统5编译安装mysql-4.1.22
  4. CentOS系统安装MySQL支持远程连接的方法
  5. Ubuntu MySQL设置同步服务器
转载请说明出处
知优网 » JDBC 连接MySQL数据库实战演示(jdbc连接MySQL数据库步骤)

发表评论

您需要后才能发表评论