使用jdbc显示空值的数据库中的值

时间:2013-04-13 15:07:15

标签: java mysql jdbc

我是JDBC的初学者。 我写了以下代码 我已经检查了表格没有正确插入值?我不知道我错在哪里?

import java.io.*;
import java.sql.*;

class Emp
{
    int eno,sal;
    String name,dept;
    Connection cn=null;
    Statement st=null;
    ResultSet rs=null;

    Emp()
    {
        try
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter Employee number:");
            eno=Integer.parseInt(br.readLine());
                    System.out.println("Enter salary:");
            sal=Integer.parseInt(br.readLine());


            System.out.println("Enter name:");
            name=(br.readLine());


            System.out.println("Enter Department:");
            dept=(br.readLine());

            Class.forName("com.mysql.jdbc.Driver");
            cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root","");
            if(cn==null)
                System.out.println(" error in connection");
            st=cn.createStatement();
            st.executeUpdate("insert into emp values(eno,sal,name,dept);");
            System.out.println("Record Inserted");

            rs=st.executeQuery("select * from emp");
            rs.first();

            System.out.println("Employee table");

            while(!rs.isLast())
            {
            System.out.println("Eno:"+rs.getInt(1)+"sal:"+rs.getInt(2)+"name:"+rs.getString(3)+"dept:"+rs.getString(4));
            rs.next();
            }   
        }
        catch(Exception e){}
    }

    public static void main(String args[]) throws Exception
    {
        Emp e=new Emp();
    }
}

问题在于此 输出显示如下

Eno:0sal:0name:dept:
Eno:0sal:0name:dept:
Eno:0sal:0name:dept:
Eno:0sal:0name:dept:
Eno:0sal:0name:dept:

1 个答案:

答案 0 :(得分:1)

您实际上并没有将变量传入SQL INSERT String,因此很有可能抛出异常但未在空异常块中报告。在这种情况下,表格将为空,在任何executeQuery

上生成空值
st.executeUpdate("insert into emp values(" + eno "," + sal + ",'" + name + "','" + dept + "');");

另外,不要让SQLException静默发生,添加

catch (SQLException sqle) {
   sqle.printStackTrace();
}

最好使用PreparedStatement来防范SQL Injection攻击。