使用java+Mysql数据库做一个简单的登录窗口界面

         最近在做项目的时候,对java连接到数据库小有体会,特此来写一篇博客给大家讲解在java中如何连接使用数据库。来展示下效果图:

 

    

     

         首先,我们来编写关于数据库里的数据操作,包括基本的增删查改以及增加的功能。我在数据库里定义了一个info库,并在库里添加了player表。player表内容如下:

可以看到,表里定义了三个变量int型scores,char类型的name与password。我写了一个 MyDBConnection类,来连接数据库,代码如下:

 

package dates;

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

public class MyDBConnection{//连接类

	private String DBDriver;
	private String DBURL;
	private String DBUser;
	private String DBPass;
	private Connection conn=null;
	private Statement stmt=null;
	public MyDBConnection(){
		DBDriver="com.mysql.jdbc.Driver";
		DBURL="jdbc:mysql://localhost:3306/info";
		DBUser="root";//用户名
		DBPass="473721601";//数据库密码
		try{
			Class.forName(DBDriver);//加载驱动程序
			//System.out.println("数据库驱动程序加载成功");
		}catch(Exception e){
			e.printStackTrace();
		}
		try{
			conn=DriverManager.getConnection(DBURL,DBUser,DBPass);//取得连接对象
			stmt=conn.createStatement();//取得SQL语句对象
			System.out.print("连接数据库成功");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public Connection getMyConnection(){
		return conn;
	}
	public Statement getMyStatement(){
		return stmt;
	}
	public void closeMyConnection(){//关闭数据库连接
		try{
			stmt.close();
			conn.close();
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	public String toString(){
		return "数据库驱动程序"+DBDriver+",链接地址"+DBURL+",用户名"+DBUser+",密码"+DBPass;
	}
}//连接类

	private String DBDriver;
	private String DBURL;
	private String DBUser;
	private String DBPass;
	private Connection conn=null;
	private Statement stmt=null;
	public MyDBConnection(){
		DBDriver="com.mysql.jdbc.Driver";
		DBURL="jdbc:mysql://localhost:3306/info";
		DBUser="root";//用户名
		DBPass="473721601";//数据库密码
		try{
			Class.forName(DBDriver);//加载驱动程序
			//System.out.println("数据库驱动程序加载成功");
		}catch(Exception e){
			e.printStackTrace();
		}
		try{
			conn=DriverManager.getConnection(DBURL,DBUser,DBPass);//取得连接对象
			stmt=conn.createStatement();//取得SQL语句对象
			System.out.print("连接数据库成功");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public Connection getMyConnection(){
		return conn;
	}
	public Statement getMyStatement(){
		return stmt;
	}
	public void closeMyConnection(){//关闭数据库连接
		try{
			stmt.close();
			conn.close();
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	public String toString(){
		return "数据库驱动程序"+DBDriver+",链接地址"+DBURL+",用户名"+DBUser+",密码"+DBPass;
	}
}

数据库连接成功后会显式数据库已连接成功。
         

 

         再来看看怎么样对数据库中的数据进行操作的:

 

	public void insertData(String name,String password,int scores){//插入操作
		try{
			String newType1=new String(name.getBytes(),"GBK");//字节转码
			String newType2=new String(password.getBytes(),"GBK");
			String sql="INSERT INTO player(scores,name,password)VALUES("+scores+",'"+newType1+"','"+newType2+"')";
			stmt.executeUpdate(sql);//更新语句
		}catch(Exception e1){
			e1.printStackTrace();
		}
	}
	

getBytes()让String对象转换为“GBK”的字节码,并可以插入到数据库中,而看sql这一句:

"INSERT INTO player(scores,name,password)VALUES("+scores+",'"+newType1+"','"+newType2+"')";

这是数据库插入操作的标准语句,意思为将scores,name,password三个数据插入到player表中,而后执行数据库的更新语句,完成插入。

 

删除:

 

public void deleteData(int mscores){
		String sql="DELETE FROM player WHERE scores="+mscores+"";
		System.out.print(sql);
		try{
			stmt.executeUpdate(sql);
			//System.out.println("一条记录被删除");
		}catch(SQLException e){
			e.printStackTrace();
		}
	}

 

 

"DELETE FROM player WHERE scores="+mscores+"";

 

这句意思为从表里删除所有scores等于mscores的数据,在这里我删除判断条件的只有数据库里的scores是否有等于mscores的,如果还需要加条件,比如要加name判断,则代码如下:

 

public void deleteData(int mscores,String mname){
		String sql="DELETE FROM player WHERE scores="+mscores+"&&name='"+mname+"'";
		System.out.print(sql);
		try{
			stmt.executeUpdate(sql);
			//System.out.println("一条记录被删除");
		}catch(SQLException e){
			e.printStackTrace();
		}
	}

从而语句变为从player表里删除scores等于mscores且name等于mname的所有数据。
修改;

 

 

public void updateData(int mscores,int scores,String name,String password){//修改
		String sql="UPDATE player SET scores="+scores+",name='"+name+"',password='"+password+"'where scores="+mscores+"&&name='"+name+"'&&password='"+password+"'";
		try{
			stmt.executeUpdate(sql);
		}catch(SQLException e){
			e.printStackTrace();
		}
	}

修改了scores的数据。

 

查询:

 

public void  selectPassword(){
		String sql="SELECT scores,name,password FROM player";
		try{
			ResultSet rs=stmt.executeQuery(sql);//返回结果集
			while(rs.next()){//指针向后移动
                         String mpassword=rs.getString("password");
 System.out.print(mpassword);}}catch(Exception e){e.printStackTrace();}}

 

查询操作多了个结果集,来获取每组数据,并用next方法来进行“指针”后移,并用getString方法将password数据读取出来。如果要读取scores的数据。则可修改代码如下:

 

 

String mscores=rs.getShort("scores");

 

 

不同的数据类型从数据库中获取的方法不同。
说完了基本操作,来看看整个的操作类:

package dates;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class DBOperation{
	private MyDBConnection myDB=null;
	private Connection conn=null;
	private Statement stmt=null;
	private int scores;
	private int number1=0;
	private int number2=0;
	private String name;
	private String password;
	public DBOperation(MyDBConnection myDB){
		conn=myDB.getMyConnection();//取得对象
		stmt=myDB.getMyStatement();//取得sql语句
	}
	public void insertData(String name,String password,int scores){
		try{
			String newType1=new String(name.getBytes(),"GBK");//字节转码
			String newType2=new String(password.getBytes(),"GBK");
			String sql="INSERT INTO player(scores,name,password)VALUES("+scores+",'"+newType1+"','"+newType2+"')";
			stmt.executeUpdate(sql);//更新语句
		}catch(Exception e1){
			e1.printStackTrace();
		}
	}
	public void deleteData(int scores){
		String sql="DELETE FROM player WHERE scores="+scores+"";
		System.out.print(sql);
		try{
			stmt.executeUpdate(sql);
			//System.out.println("一条记录被删除");
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	public void updateData(int mscores,int scores,String name,String password){//修改
		String sql="UPDATE player SET scores="+scores+",name='"+name+"',password='"+password+"'where scores="+mscores+"&&name='"+name+"'&&password='"+password+"'";
		try{
			stmt.executeUpdate(sql);
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	public boolean  selectPassword(String mpassword){//查询密码
		String sql="SELECT scores,name,password FROM player";
		try{
			ResultSet rs=stmt.executeQuery(sql);//返回结果集
			while(rs.next()){//指针向后移动
				password=rs.getString("password");
				number2++;
				//System.out.print(rs.getString("password")+"  ");
				if(password.equals(mpassword)&&(number2==number1)){
					//System.out.print("number2:"+number2);
					return true;
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	public boolean selectName(String mname){//查询id
		String sql="SELECT scores,name,password FROM player";
		try{
			ResultSet rs=stmt.executeQuery(sql);//返回结果集
			while(rs.next()){//指针向后移动
				name=rs.getString("name");
				number1++;
				if(name.equals(mname)){
					//System.out.print("number1:"+number1);
					return true;
				}
			}
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	public int getScores(){
		return scores;
	}
	public String getName(){
		return name;
	}
	public String getPassword(){
		return password;
	}
	
	public void setNumber1(){
		number1=0;
	}
	public void setNumber2(){
		number2=0;
	}
}


代码中写了bool类型的selectName与selectPassword方法,并用number1与number2记录name与password在数据库的位置,登录操作实际的思路是在先在数据库中查找用户id,如果查到了就记录此id在第几个位置,并将位置传入selectPassword方法,进行查询密码匹配,判断密码和用户输入的密码是否相同且该密码的位置是否和id的位置相同。如果没找到该id,则提示用户注册,注册其实就是在数据库中插入数据。
下面来看看,一个简单的界面窗口类:

 

 

 

package ui;

import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;

import dates.DBOperation;
import dates.MyDBConnection;

public class Window implements MouseListener {

	public JFrame frame = new JFrame("登录窗口");
	private JLabel label1=new JLabel("游戏id:");
	private JTextField txt1=new JTextField();
	private JLabel label2=new JLabel("密   码:");
	private JTextField txt2=new JTextField();
	private JButton btn1=new JButton("登陆");
	private JButton btn2=new JButton("注册");
	private JButton btn3=new JButton("退出");
	private String text1;
	private String text2;
	private int distinguish;//用来记录鼠标悬停在哪个位置
	MyDBConnection myDB=new MyDBConnection();
	public DBOperation myOpr=new DBOperation(myDB);
	public Window(){
	
	}
	
	public void show(){
		frame.setLayout(null);//定义空布局
		frame.setSize(470,300);
		frame.setLocation(400, 200);
		
		Font font=new Font("华文行楷",Font.BOLD,20);
		label1.setFont(font);
		label1.setForeground(Color.gray);//设置字体颜色
		label2.setFont(font);
		
		label2.setForeground(Color.gray);
		txt1.setOpaque(false);//设置文本框透明
		txt2.setOpaque(false);
		
		btn1.setContentAreaFilled(false);//设置button组件透明
		btn1.setFont(font);
	        btn1.setForeground(Color.gray);
	        btn1.setBorder(BorderFactory.createRaisedBevelBorder());//设置突出button组件
	        btn2.setContentAreaFilled(false);
		btn2.setFont(font);
		btn2.setBorder(BorderFactory.createRaisedBevelBorder());
	        btn2.setForeground(Color.gray);
	        btn3.setContentAreaFilled(false);
		btn3.setFont(font);
		btn3.setBorder(BorderFactory.createRaisedBevelBorder());
	        btn3.setForeground(Color.gray);
		JPanel bj = new JPanel() {//设置背景
			protected void paintComponent(Graphics g) {
				Image bg;
				try {
					bg = ImageIO.read(new File("src/image/开始背景.PNG"));
					g.drawImage(bg, 0, 0, getWidth(), getHeight(), null);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
	
	       label1.setBounds(100,50,100,100);
		txt1.setBounds(180,90, 150, 20);
		label2.setBounds(100,80,100,100);
		txt2.setBounds(180,120, 150, 20);
		btn1.setBounds(100,200,80,20);
		btn2.setBounds(190,200,80,20);
		btn3.setBounds(280,200,80,20);
		frame.setContentPane(bj);
		frame.setLayout(null);
		frame.add(label1);
		frame.add(txt1);
		frame.add(label2);
		frame.add(txt2);
		frame.add(btn1);
		frame.add(btn2);
		frame.add(btn3);
		btn1.addMouseListener(this);//添加鼠标监听
		btn2.addMouseListener(this);
		btn3.addMouseListener(this);
		frame.setVisible(true);	
	}
	
	public void mouseClicked(MouseEvent arg0) {
	   text1=txt1.getText();//获取用户输入数据
	   text2=txt2.getText();
	   if(distinguish==1){
	   if(myOpr.selectName(text1)){//登录判断
		   if(myOpr.selectPassword(text2)){
			   JOptionPane.showMessageDialog(null, "登陆成功","提示",2);
				txt1.setText("");
				txt2.setText("");
				distinguish=4;
				frame.setVisible(false);//登录成功则关闭界面
		   }else{
				JOptionPane.showMessageDialog(null, "密码错误","提示",2);
				txt2.setText("");
				myOpr.setNumber1();//密码错误将number置0
				myOpr.setNumber2();
		   }
	   }else{
		   JOptionPane.showMessageDialog(null, "此id不存在,请注册","提示",2);
			txt1.setText("");
			txt2.setText("");
	   }
	   }
	   if(distinguish==2){
		   
		   String logi=(String) JOptionPane.showInputDialog(null,"请输入你的id:\n","注册",JOptionPane.PLAIN_MESSAGE,null,null,"在这输入"); 
		   String pas=(String) JOptionPane.showInputDialog(null,"请输入你的密码:\n","注册",JOptionPane.PLAIN_MESSAGE,null,null,"在这输入");
			myOpr.insertData(logi,pas,0);
			JOptionPane.showMessageDialog(null, "注册成功","提示",2);
	   }
	   if(distinguish==3){
		   int n = JOptionPane.showConfirmDialog(null, "是否退出?", "游戏结束",JOptionPane.YES_NO_OPTION);
		   myDB.closeMyConnection();
			if(n==JOptionPane.YES_OPTION){
			System.exit(1);
			}
	   }
	   
	}

	public void mouseEntered(MouseEvent arg0) {
		if (arg0.getSource() == btn1) {
			distinguish=1;//鼠标悬停在btn1处则把distinguish置1
			btn1.setForeground(Color.red);//改变颜色
			btn1.setBorder(BorderFactory.createLoweredBevelBorder());//组件凹陷
			btn2.setForeground(Color.gray);
			btn2.setBorder(BorderFactory.createRaisedBevelBorder());
			btn3.setForeground(Color.gray);
			btn3.setBorder(BorderFactory.createRaisedBevelBorder());
		}
		if (arg0.getSource() == btn2) {
			distinguish=2;
			btn1.setForeground(Color.gray);
			btn1.setBorder(BorderFactory.createRaisedBevelBorder());
			btn2.setForeground(Color.red);
			btn2.setBorder(BorderFactory.createLoweredBevelBorder());
			btn3.setForeground(Color.gray);
			btn3.setBorder(BorderFactory.createRaisedBevelBorder());
		}
		if (arg0.getSource() == btn3) {
			distinguish=3;
			btn1.setForeground(Color.gray);
			btn1.setBorder(BorderFactory.createRaisedBevelBorder());
			btn2.setForeground(Color.gray);
			btn2.setBorder(BorderFactory.createRaisedBevelBorder());
			btn3.setForeground(Color.red);
			btn3.setBorder(BorderFactory.createLoweredBevelBorder());
			}

	}
	public void mouseExited(MouseEvent arg0) {//鼠标退出三个button组件后恢复
		distinguish=0;
		label1.setForeground(Color.gray);
		label2.setForeground(Color.gray);
		txt1.setOpaque(false);
		txt2.setOpaque(false);
		btn1.setContentAreaFilled(false);
	    btn1.setForeground(Color.gray);
	    btn1.setBorder(BorderFactory.createRaisedBevelBorder());
	    btn2.setContentAreaFilled(false);
		btn2.setBorder(BorderFactory.createRaisedBevelBorder());
	    btn2.setForeground(Color.gray);
	    btn3.setContentAreaFilled(false);
		btn3.setBorder(BorderFactory.createRaisedBevelBorder());
	    btn3.setForeground(Color.gray);
	}
	
	public void mousePressed(MouseEvent arg0) {
			
	}
	public void mouseReleased(MouseEvent arg0) {
		
		
	}
	public String getText1(){
		return text1;
	}
	public String getText2(){
		return text2;
	}
	public int getDistinguish(){
		return distinguish;
	}
	
}


到此为止,所有的登录界面的介绍已完成,下面是登录的背景材料和完整的代码。

 

 

 

代码链接:https://pan.baidu.com/s/1_AFdIFe01WKSUa0lEPD3-Q

 

具体的代码在这个练手的项目里:...,https://github.com/suyeq/java-fly-fight,一个飞机大战小项目

 

 

 

好的,对于这个问题,我们需要先创建一个数据库以及一张用户表,包含用户名和密码两个字段。然后在Java中连接数据库、查询用户信息、进行密码验证等操作。 以下是一个简单的示例代码,供参考: ```java import java.sql.*; public class LoginWindow { private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database_name"; private static final String USER = "your_username"; private static final String PASSWORD = "your_password"; public static void main(String[] args) { // 创建窗口界面等代码省略... // 处理登录事件 loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username = usernameField.getText(); String password = new String(passwordField.getPassword()); if (validateUser(username, password)) { // 登录成功,跳转到主界面等代码省略... } else { // 登录失败,提示用户等代码省略... } } }); } private static boolean validateUser(String username, String password) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { // 连接数据库 conn = DriverManager.getConnection(DB_URL, USER, PASSWORD); // 执行查询 String sql = "SELECT * FROM user WHERE username = ? AND password = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, username); stmt.setString(2, password); rs = stmt.executeQuery(); if (rs.next()) { // 用户名和密码匹配 return true; } else { // 用户名和密码不匹配 return false; } } catch (SQLException ex) { ex.printStackTrace(); return false; } finally { // 释放资源 try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException ex) { ex.printStackTrace(); } } } } ``` 需要注意的是,以上代码仅为示例,实际应用中需要对输入进行合法性检查,防止SQL注入等安全问题。同时,建议将数据库连接等重要信息存放在配置文件中,避免硬编码。
评论 72
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值