Java连接mysql数据库

/*
 * java连接数据库Myslq及对数据库的一些操作方法
 * 首先得把驱动包放在Java安装包里的JRE下的lib/ext下:C:\Program Files\Java\jre1.5.0_11\lib\ext
 * 然后mysql服务一定要起动
 * 注意:在用SQL查询Password时,一定要把Password(JPasswordField/Char型)转换成String型
 */

package javadb;

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class DbJava {
    private static  Connection connDB()throws SQLException{
     try {
   Class.forName("com.mysql.jdbc.Driver");
  }
     catch (ClassNotFoundException e)
     {
   e.printStackTrace();
  }
      Connection conn=null;
      conn=DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8","root","111");
      return conn;
       }


    /*
     * 查询此用户是否存在
     * 按用户名和密码查询
     */
    public void queryByName(String name,char[] password)
    {
     String pwd = String.valueOf(password);
     String sql = "select * from user_info where u_name = '" + name + "' and u_password = '" + pwd + "' ";
     Connection conn = null;
     Statement st = null;
     ResultSet rs = null;
     try
     {
      conn = connDB();
      st = conn.createStatement();
      rs = st.executeQuery(sql);
      if(!rs.next())
          JOptionPane.showMessageDialog(null, "此用户不存在或密码错误!", "error",JOptionPane.ERROR_MESSAGE);
      else
       JOptionPane.showMessageDialog(null, "下一步的操作", "Next",JOptionPane.YES_OPTION);
     }
     catch(SQLException e)
     {
      System.out.print("Exception" + e.getMessage());
     }
    }
   
}

你可能感兴趣的:(java,sql,mysql,swing,ext)