我正在尝试将 SQLite 与 java 一起使用,我写了一段给出三个字符串的代码
必须填充表格
|---------------------|
|ID|NAME|SNAME1|SNAME2|
|1 |Ale |test |test2 |
|---------------------|
我怎么能自动增加ID?我尝试在创建表时使用auto_increment,但是在填充表时遇到了异常,所以我正在寻找一种好方法。
从代码中可以看出,每次执行程序时我都只能插入一行。
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
/**
*
* @author MITROTTA
*/
public class Database {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws SQLException {
Connection c = null;
Statement stmt = null;
String sql;
//Variabili Database
String name;
String sname1, sname2;
Scanner in = new Scanner(System.in);
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
//Creazione tabella
stmt = c.createStatement();
sql = "CREATE TABLE IF NOT EXISTS COMPANY " +
"(ID INT PRIMARY KEY NOT NULL," +
" NAME CHAR(30) NOT NULL, " +
" SNAME1 CHAR(30) NOT NULL, " +
" SNAME2 TEXT)";
stmt.executeUpdate(sql);
System.out.print("Type name: ");
name = in.nextLine();
System.out.print("Type sname1: ");
sname1 = in.nextLine();
System.out.print("Type sname2: ");
sname2 = in.nextLine();
sql = "INSERT INTO COMPANY (ID,NAME,SNAME1,SNAME2) " +
"VALUES (2, '" + name + "','" + sname1 + "','" + sname2 + "');";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery( "SELECT * FROM COMPANY;" );
while ( rs.next() ) {
int id = rs.getInt("ID");
String name1 = rs.getString("NAME");
String name2 = rs.getString("SNAME1");
String name3 = rs.getString("SNAME2");
System.out.println( "ID = " + id );
System.out.println( "Name = " + name1 );
System.out.println( "SName1 = " + name2 );
System.out.println( "SName3 = " + name3 );
System.out.println();
}
rs.close();
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Table created successfully");
}
}
答案 0 :(得分:3)
要获得autoincrementing column,您需要将其声明为INTEGER PRIMARY KEY
(而不是INT
)。
然后你可以插入一个NULL值,或者省略INSERT语句中的列。
答案 1 :(得分:1)
在插入过程中只使用NULL
值代替id
,您可能不应将其声明为NOT NULL
。
资料来源:http://www.sqlite.org/faq.html#q1