我是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:
答案 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攻击。