这是我想使用insertData()
方法的主要类。这个方法来自不同的类InsertOperation
,两个类都在同一个包中,但我仍然不能使用该方法。我是java的新手,我还在努力掌握它。
package crudoperations;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.*;
public class CRUDOperations {
/*
private static final String CREATE_TABLE = "CREATE TABLE employee "
+ "(" + "user_id INT(100) NOT NULL PRIMARY KEY," +
"first_name VARCHAR(100)," +
"last_name VARCHAR(100)," +
"contact_number INT(10)," +
"email_id VARCHAR(100))";
*/
public static void main(String[] args) throws SQLException {
Connection con = null;
PreparedStatement stmt = nulll;
try{
con = // File enter code here Connection.getConnection();
InsertOperation iop = InsertOperation(); //Showing error in this line
iop.insertData();
//System.out.println("Connected");
//stmt = con.prepareStatement(CREATE_TABLE);
//stmt.executeUpdate();
//System.out.println("Table Created");
}
catch(SQLException e){
System.err.print(e);
}
finally{
if(con != null){
con.close();
}
}
}
}
下面是InsertOperation类的代码:
package crudoperations;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class InsertOperation {
public void insertData() throws SQLException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the First Name: ");
String user_firstname = sc.next();
System.out.println("Enter the Last Name: ");
String user_lastname = sc.next();
System.out.println("Enter the Contact Number: ");
String user_contact = sc.next();
System.out.println("Enter the Email ID: ");
String user_email = sc.next();
Connection con = null;
con = FileConnection.getConnection();
PreparedStatement pst = con.prepareStatement(
"INSERT INTO employees "
+ " (user_id, first_name, last_name, contact_number, email_id)"
+ " VALUES (?,?,?,?)");
pst.setString(2, user_firstname);
pst.setString(3, user_lastname);
pst.setString(4, user_contact);
pst.setString(5, user_email);
int i = pst.executeUpdate();
if(i != 0){
System.out.print("success");
}
else{
System.out.print("error");
}
}
}
错误如下:
error: cannot find symbol
InsertOperation iop = InsertOperation();
symbol: method InsertOperation()
location: class CRUDOperations
如果要访问instance方法,需要创建一个实例。
InsertOperation iop = new InsertOperation();
我想你可能忘记这里的新关键词了。
否则,在声明insertData()方法时可以使用静态关键字,如下所示。
public static void insertData() throws SQLException
然后调用方法名访问那个方法
Ex: insertData();
缺失"new"创建对象的关键字。
```
InsertOperation iop = InsertOperation(); //Showing error in this line
```
应该
InsertOperation iop = new InsertOperation();