为什么它错误无法在
中找到符号PreparedStatement ps = connection.prepareStatement(sql);
^
variable connection
但变量连接已经声明如下: *我输入正确的用户名,密码和网址
try {
Class.forName("org.postgresql.Driver");
}
catch (java.lang.ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
String url = "jdbc:postgresql://stampy.db.elephantsql.com/";
String username = "";
String password = "";
Connection connection = DriverManager.getConnection(url, username, password);
List<AdvDetail> list = new ArrayList();
} catch(SQLException e) {
System.out.println(e.getMessage());
}
我有导入库
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.*;
import a1.kmita.com.model.Adv;
import a1.kmita.com.model.AdvDetail;
import a1.kmita.com.listener.ExceptionListener;
import a1.kmita.com.model.Response;
和其他弹簧库
这里是代码
try {
String sql = "INSERT INTO advert (ad_title, ad_desc, ad_price, ad_image1,) VALUES (?, ?, ?, ?)"; /* this is the query */
PreparedStatement ps = connection.prepareStatement(sql); /* this is error */
ps.setString(1, product_name);
ps.setString(2, product_desc);
ps.setInt(3, product_price);
ps.setString(4, image1);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
System.out.println(e.getMessage());
}
答案 0 :(得分:0)
在使用之前,您尚未创建连接对象。查看此示例:
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(DB_URL,USERNAME,PASS);
答案 1 :(得分:0)
connection
是可变的,必须使用您的连接属性进行初始化。仅仅导入包是不够的。
你可以这样做(例如对于postgresql):
Connection connection = null;
try{
Class.forName("org.postgresql.Driver");
String connectionString = "jdbc:postgresql://" + dbhost + ":" + dbport + "/" + dbname;
connection = DriverManager.getConnection(connectionString, dbuser, dbpassword)
}catch (Exception e){
//...
}
编辑:变量的声明必须在try块之前,否则变量在try块的范围内。对我的例子说,你怎么做。