你好##我只是一个初学者,我想分享我的工作。
始终为连接数据库创建不同的类。这将使您的代码更干净。
我将用一个例子向你展示
private void btn_LoginActionPerformed(java.awt.event.ActionEvent evt) {
/*LOGIC*/
super.Show("Select * from Login");// this class is extending a class connect me
try{
int Checker = 0;// a flag
while(rs.next())
{
String user = field_UserId.getText();//values coming from field
String pass = field_Password.getText();
String user1 = rs.getString("User");//values coming from database
String pass1 = rs.getString("Pass");
if( user.equals(user1)& pass.equals(pass1))
{
//if enters into loop user is valid
Checker=1;//setting flag to 1
}
}
if(Checker == 0 )
{ JOptionPane.showMessageDialog(null,"Check Id&Password");
field_UserId.setText("");
field_Password.setText("");
}
}
catch(Exception ex_connection)
{
System.out.println(ex_connection);
}
/*LOGIC ENDED */
}
**现在上课connectme * *
class Connectme
{
String Name;
String Number;
ResultSet rs,r,rs1;
ResultSetMetaData md;
Statement st;
Statement st1;
int p=0;
Connectme()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/Storage","root","");
st= con.createStatement();
st1 = con.createStatement();
}
catch(Exception ex_connection)
{
System.out.println("damnnn");
JOptionPane.showMessageDialog(null,"Check Database Connection");
}
}
void queryExecute(String insert)
{
try
{
/*begin-to execute query ins database*/
st.executeUpdate(insert);
/*end-to enter values in database*/
}
catch(Exception ex_connection)
{
System.out.println(ex_connection);
}
}
void Show(String table_name)
{
try
{
String insert = ("Select * from " + table_name + "");
rs = st1.executeQuery(insert);
md = rs.getMetaData();
}
catch(Exception ex_connection)
{
System.out.println(ex_connection);
System.out.println("waah");
}
}
void Show1(String insert1)
{
try
{
rs1= st.executeQuery(insert1);
/* while (rs1.next()) {
System.out.print(rs1.getString("Price"));
}*/
md = rs1.getMetaData();
}
catch(Exception ex_connection)
{
System.out.println(ex_connection);
}
}
}
解决您的问题
String user=username_field.getText();
PreparedStatement ps = con.prepareStatement(
"SELECT ID, username, password FROM person where username=user" );