import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
fun main(args: Array<String>) {
val connection: Connection
val connectionUrl = "jdbc:sqlite:userdatabase.db"
try {
connection = DriverManager.getConnection(connectionUrl)
val statement = connection.createStatement()
statement.execute("CREATE TABLE IF NOT EXISTS users (first_name TEXT, last_name TEXT, address TEXT, phone_number TEXT)")
} catch (e: SQLException) {
e.printStackTrace()
}
// Add a user to the database
addUser("John", "Doe", "123 Main Street", "555-555-5555")
// Remove a user from the database
removeUser("John", "Doe")
}
fun addUser(firstName: String, lastName: String, address: String, phoneNumber: String) {
val connection: Connection
val connectionUrl = "jdbc:sqlite:userdatabase.db"
try {
connection = DriverManager.getConnection(connectionUrl)
val statement = connection.prepareStatement("INSERT INTO users (first_name, last_name, address, phone_number) VALUES (?, ?, ?, ?)")
statement.setString(1, firstName)
statement.setString(2, lastName)
statement.setString(3, address)
statement.setString(4, phoneNumber)
statement.executeUpdate()
} catch (e: SQLException) {
e.printStackTrace()
}
}
fun removeUser(firstName: String, lastName: String) {
val connection: Connection
val connectionUrl = "jdbc:sqlite:userdatabase.db"
try {
connection = DriverManager.getConnection(connectionUrl)
val statement = connection.prepareStatement("DELETE FROM users WHERE first_name = ? AND last_name = ?")
statement.setString(1, firstName)
statement.setString(2, lastName)
statement.executeUpdate()
} catch (e: SQLException) {
e.printStackTrace()
}
}
This program uses the SQLite database and the JDBC API to connect to the database and execute SQL statements. The addUser
function inserts a new row into the users
table with the provided first name, last name, address, and phone number. The removeUser
function deletes the row from the users
table that matches the provided first and last name.
The program assumes that the SQLite JDBC driver is in the classpath. You will need to include the driver in your project dependencies in order to run this program.Regenerate response