首页 > 代码库 > Java连接MySQL随笔

Java连接MySQL随笔

//连接时要注意所有jar,以及环境搭建好;

package util;

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

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class Jdbc {
    public static void main(String[] args){
    
  // 驱动程序名
    
  String driver = "com.mysql.jdbc.Driver";

  // URL指向要访问的数据库名scutcs

  String url = "jdbc:mysql://127.0.0.1:3306/golden";

  // MySQL配置时的用户名

  String user = "root";

  // Java连接MySQL配置时的密码

  String password = "1234";


  try {

  // 加载驱动程序

  Class.forName(driver);

  // 连续数据库

  Connection conn = (Connection) DriverManager.getConnection(url, user, password);

  if(!conn.isClosed())

  System.out.println("已成功连接!");

  // statement用来执行SQL语句

  Statement statement = (Statement) conn.createStatement();

  // 要执行的SQL语句

  String sql = "select * from golden.users";

  //结果集

  ResultSet rs = statement.executeQuery(sql);
  System.out.println("----------------------------------");
  System.out.println("执行结果如下所示:");
  System.out.println("----------------------------------");
  System.out.println(" UsersId" + "\t" + "UsersName"+ "\t" + "pwd"+ "\t" + "age");
  System.out.println("----------------------------------");
  String usersName = null;
  String pwd=null;
  Integer age=0;
  while(rs.next()) { 
   
  //选择数据
   
  usersName = rs.getString("usersName");
  pwd=rs.getString("pwd");
  age=rs.getInt(4); //索引,也可用age;

  // 输出结果

  System.out.println(rs.getString("usersId") + "\t" + usersName+ "\t" + pwd+ "\t" + age);
  } 
  rs.close();
  conn.close();
  } catch(ClassNotFoundException e) {
   System.out.println("Sorry,can`t find the Driver!");
   e.printStackTrace(); 
   } catch(SQLException e) {
    e.printStackTrace();
    } catch(Exception e) {
     e.printStackTrace();
     }  
  }