Summary: in this tutorial, you will learn how to create a new table in an SQLite database from a Java program using SQLite JDBC Driver.
To create a new table in a specific database, you use the following steps:
- First, prepare a
CREATE TABLE
statement to create the table you want. - Second, connect to the database.
- Third, create a new instance of the
Statement
class from aConnection
object. - Fourth, execute the
CREATE TABLE
statement by calling theexecuteUpdate()
method of theStatement
object.
The following program illustrates the steps of creating a table.
package net.sqlitetutorial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author sqlitetutorial.net
*/
public class Main {
/**
* Create a new table in the test database
*
*/
public static void createNewTable() {
// SQLite connection string
String url = "jdbc:sqlite:C://sqlite/db/tests.db";
// SQL statement for creating a new table
String sql = "CREATE TABLE IF NOT EXISTS warehouses (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text NOT NULL,\n"
+ " capacity real\n"
+ ");";
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
// create a new table
stmt.execute(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
createNewTable();
}
}
Code language: Java (java)
In this tutorial, you have learned how to create a new table in an SQLite database from a Java program using the SQLite JDBC driver.
Was this tutorial helpful ?