package Login1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Login1 {
JFrame jFrame;
public static void main(String[] args) {
// TODO Auto-generated method stub
new Login1().init();
}
public void init()
{
jFrame=new JFrame();
jFrame.setBounds(100, 100, 1000, 1000);
jFrame.setLayout(null);
JTextField userNameT=new JTextField();
userNameT.setBounds(100, 100, 150,50);
jFrame.add(userNameT);
JTextField passwordT=new JTextField();
passwordT.setBounds(300, 100,150, 50);
jFrame.add(passwordT);
JButton jButton=new JButton("登录");
jButton.setBounds(0, 300, 50, 50);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//1.驱动实例化
String className="com.mysql.jdbc.Driver";
try {
Class.forName(className);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//2.创建数据库连接
String url="jdbc:mysql://localhost:3306/user?useSSL=false&serverTimezone=UTC";
String userString="root";
String name=userNameT.getText().trim();
String password=passwordT.getText().trim();
String passwordString="root1";
try {
Connection connection=DriverManager.getConnection(url, userString, passwordString);
//3.构建查询器
Statement statement=connection.createStatement();
//4.1创建SQL语句
String sql="select * from login where ";
sql+="userName= '"+name+"' AND password='"+password+"'";
//4.2执行SQL语句
ResultSet resultSet=statement.executeQuery(sql);
if(resultSet.next())
System.out.println("登录成功");
else {
System.out.println("登录失败");
}
/*第二种登录
* resultSet.last();//使游标到达最底层;游标指向最后的行号,也就是总行数
int count=resultSet.getRow();//游标移动,判断是否有数据
if(count>0)
System.out.println("登录成功");
*/
/*第三种登录
* sql只查询账号,然后跟第二种一样, 而提示是用户存在,
*resultSet.beforeFirst();
*while(resultSet.next())
{
String dbPW=resultSet.getString("password");
if(dbPW.equals(pw))
登录成功
else {
登录失败
}
}
*/
//5.关闭数据库
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
jFrame.add(jButton);
jFrame.setVisible(true);
}
}
Java与数据库登录
最新推荐文章于 2022-08-13 16:42:29 发布