Java检查值是否存在于数据库中 [英] Java checking whether the value exists in database

查看:987
本文介绍了Java检查值是否存在于数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在研究Java和MySQL.我的实现如下:

hello i am working on java and MySQL. My implementation are as follows :

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.sql.*;
import java.util.Scanner;

public class BankingSystem extends JFrame {
    public static void main(String[] args) throws Exception{
        int ur=0;
        int PIN;
        String ID;
        Scanner s=new Scanner(System.in);
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/BankingSystem";
        String user = "root";
        String pass="";
        Connection con = DriverManager.getConnection(url,user,pass);
        Statement st = con.createStatement();
        System.out.println("Enter Your 4 digit PIN");
        PIN=s.nextInt();

        ResultSet rs=st.executeQuery("select * from customerinformation where pin ="+PIN);
//checking for existance of user entered pin
if((rs.getString(1)).equals("")){System.out.println("Invalid PIN");}


        while(rs.next())
        {

            System.out.println(rs.getString(1)+"  "+rs.getString(2)+"  "+rs.getString(3)+"  "+rs.getString(4));

        }

    }

}

,但是此代码不起作用.给出某种异常错误,但是当我删除包含if语句的行时,它工作正常.如何检查引脚是否有效.

but this code is not working. Giving some sort of exception error but when i remove the line containing if statement then it work fine.How do i check whether the pin is valid or not.

它具有以下异常:

Exception in thread "main" java.sql.SQLException: Before start of result set
        at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:3624)
        at com.mysql.jdbc.ResultSet.getString(ResultSet.java:1762)
        at BankingSystem.main(BankingSystem.java:22)

推荐答案

尝试这种方式 替换此Statement st = con.createStatement();

try this way Replace this Statement st = con.createStatement(); with

String query ="select * from customerinformation where pin =?"
PreparedStatement st =con.prepareStatement("query");
st.setInt(1,PIN);
ResultSet resultSet = st.executeQuery();

您永远不要在PreparedStatement上使用Statement

You should never use Statement over PreparedStatement

if (!resultSet.next() ) {
    System.out.println("resultset does not data");
} else {

    do {
        System.out.println(rs.getString(1)+"  "+
                           rs.getString(2)+"  "+
                          rs.getString(3)+"  "+
                          rs.getString(4));


    } while (resultSet.next());
}

这篇关于Java检查值是否存在于数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆