代码:
img{ width:100%; }
我想从用户那里获取输入并保存到sql db中。但我无法制作我想要的代码。 运行此代码会收到错误:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class NewTry {
public static void main(String[] args) {
// TODO Auto-generated method stub
String dep,namee,cnic,cell;
int id;
id=Integer.parseInt(txtTeacherId.getText());
namee=txtTeacherName.getText();
dep=cmbDepName.getSelectedItem().toString();
cnic=txtTeacherCnicNo.getText();
cell=txtTeacherCellNo.getText();
try
{
// try
// {
// // create a mysql database connection
// String myDriver = "org.gjt.mm.mysql.Driver";
// String myUrl = "jdbc:mysql://localhost/test";
// Class.forName(myDriver);
// Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
//
//Class.forname("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
// JOptionPane.showMessageDialog(null,n);
String insertSql = "INSERT INTO Teacher VALUES (?, ?, ?, ?, ?)";
PreparedStatement pInsertTeacher = conn.prepareStatement(insertSql);
// pInsertTeacher=conn.prepareStatement("INSERT INTO TEACHER VALUES(?,?,?,?,?)");
pInsertTeacher.setInt(1,id);
pInsertTeacher.setString(2,namee);
pInsertTeacher.setString(3,dep);
pInsertTeacher.setString(4,cnic);
pInsertTeacher.setString(5,cell);
pInsertTeacher.executeUpdate();
//preparedStmt.execute();
System.out.println("Data inserted Successfully Check your SQL table");
}
catch(ClassNotFoundException e)
{
System.out.println(e.toString());
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Record Already Inserted....");
}
}
}
答案 0 :(得分:0)
您的代码基本上无法编译。在线
id=Integer.parseInt(txtTeacherId.getText());
namee=txtTeacherName.getText();
dep=cmbDepName.getSelectedItem().toString();
cnic=txtTeacherCnicNo.getText();
cell=txtTeacherCellNo.getText();
您正在使用尚未声明的变量。试试
Console c = System.console();
id=Integer.parseInt(c.readLine("Insert teacher ID: "));
namee=c.readLine("Insert teacher name: ");
dep=c.readLine("Insert teacher department: ");
cnic=c.readLine("Insert teacher cnic: ");
cell=c.readLine("Insert teacher cell: ");
代替。当然,如果您想使用用户界面来定义数据,您应该选择Java AWT,Java SWING或Java FX教程。