网络编程
位置:首页>> 网络编程>> 数据库>> Java连接mysql数据库代码实例程序

Java连接mysql数据库代码实例程序

作者:沃德吉尔·邦英  发布时间:2024-01-22 03:01:26 

标签:java,连接,mysql,数据库

这篇文章主要介绍了java连接mysql数据库代码实例程序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

用java 联接mysql的实例

在联接的时候,先确保本机安装了mysql或者服务器是安装了mysql


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MainSql {
 // JDBC 驱动名及数据库 URL
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://localhost:3306/chat";

// 数据库的用户名与密码,需要根据自己的设置
 static final String USER = "root";
 static final String PASS = "";
 public static void main(String[] args) {
   // TODO Auto-generated method stub
   Connection conn = null;
   Statement stmt = null;
   try{
     Class.forName(JDBC_DRIVER);
     System.out.println("链接数据库..");
     conn = DriverManager.getConnection(DB_URL,USER,PASS);
     stmt = conn.createStatement();
     String sql = "SELECT * FROM users";
     ResultSet rs = stmt.executeQuery(sql);
     while(rs.next()){
       // 通过字段检索
       String id = rs.getString("id");
       String password = rs.getString("passwd");

// 输出数据
       System.out.println("用户名: " + id);
       System.out.println("密码: " + password);
     }
     rs.close();
     stmt.close();
     conn.close();
   }catch(SQLException se){
     // 处理 JDBC 错误
     se.printStackTrace();
   }catch(Exception e){
     // 处理 Class.forName 错误
     e.printStackTrace();
   }finally{
     // 关闭资源
     try{
       if(stmt!=null) stmt.close();
     }catch(SQLException se2){
     }// 什么都不做
     try{
       if(conn!=null) conn.close();
     }catch(SQLException se){
       se.printStackTrace();
     }
   }
   System.out.println("Goodbye!");
 }
}

这就是mysql联接的实例程序,这里我就只粘贴了java调用mysql,bingqie建立联接的代码,并没有调用到sql语句,其他部分可以在网上找到

来源:https://www.cnblogs.com/loveshit/p/11923071.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com