我试图创建一个表,插入表中并使用Derby打印表的内容(如下所示)。
TestProject类:
package com.user.DerbyTest;
public class TestProject {
public static void main(String[] args) {
DBConnection db = new DBConnection();
db.createTable();
db.insertIntoTable("todd", 23, 'M');
db.insertIntoTable("wayne", 54, 'M');
db.printAll();
}
}
DBConnection类:
package com.user.DerbyTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection {
private static final String DRIVER = "org.apache.derby.jdbc.*";
private static final String JDBC_URL = "jdbc:derby:derbytest;create=true";
Connection conn;
public DBConnection(){
try {
this.conn = DriverManager.getConnection(JDBC_URL);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (this.conn != null){
System.out.println("Connected to database.");
}
}
public void createTable(){
try {
conn.createStatement().execute("Create TABLE MyDerbytable(Name varchar(50), Age INT, Gender char(1))");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void insertIntoTable(String name, int age, char gender){
try {
conn.createStatement().execute("INSERT INTO MyDerbytable Values ("+name+","+age+","+gender+")");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printAll(){
try {
Statement statement = this.conn.createStatement();
ResultSet res = statement.executeQuery("Select * FROM MyDerbytable");
while(res.next()){
System.out.println(res.getString("Name") + res.getString("Age") + res.getString("Gender"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我在尝试运行时遇到了大量错误:
有什么想法吗?
编辑:更改为DROP错误:
答案 0 :(得分:1)
你的桌子已退出。尝试DROP TABLE myderbytable;
答案 1 :(得分:0)
您的第一个INSERT语句将最终成为:
INSERT INTO MyDerbytable Values (todd,23,M)
您在todd
和M
值附近没有引号,因此将其视为对列名称的引用,为您提供错误。您必须用单引号括起这样的文字值:
INSERT INTO MyDerbytable Values ('todd',23,'M')
所以你的插入代码可能是:
"INSERT INTO MyDerbytable Values ('"+name+"','"+age+"','"+gender+"')"
(注意额外的'字符)。
但是像你一样连接字符串会让你对SQL Injection Attacks敞开大门。如果您的任何输入包含引号字符,它也会给您带来问题。了解如何使用PreparedStatement
。