I was assigned to make a Java program that accepts SQL queries from a text file line by line, with line 1 being the driver name, line 2 is the URL, line 3 and 4 is the username and password respectively and line 5 is the query. So for example my text file would have the following:
org.apache.derby.jdbc.ClientDriver
jdbc:derby://localhost:1527/STUDENTDB
app
app
SELECT * FROM StudentDb WHERE STUDENT_NAME = ?
Jesse
And here is the code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import static java.lang.Boolean.parseBoolean;
import static java.lang.Integer.parseInt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
public class TestPreparedStatement {
public static void main (String args[]) throws FileNotFoundException, IOException {
try {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\PCUSER\\info.txt"));
String driver = br.readLine();
Class.forName(driver);
System.out.println("LOADED DRIVER ---> " + driver);
String url = br.readLine();
Connection con = DriverManager.getConnection (url, br.readLine(), br.readLine());
System.out.println("CONNECTED TO ---> "+ url);
String queryStr = br.readLine();
PreparedStatement ps = con.prepareStatement(queryStr);
String argu = br.readLine();
ps.setString(1, argu);
String queryStr2 = br.readLine();
ResultSet rs = ps.executeQuery();
System.out.println("EXECUTED QUERY ---> " + queryStr);
System.out.println("\nPROCESSING RESULTS:\n");
while (rs.next())
{
System.out.println("Name: " + rs.getString("STUDENT_NAME").trim());
System.out.println("Student Number: " + rs.getString("STUDENT_NUMBER").trim());
System.out.println("Course: " + rs.getString("COURSE").trim());
}
rs.close();
ps.close();
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
The SELECT command I managed to make it work but I'm not sure how I can implement other query commands like INSERT INTO and DELETE. Like for example if I wanted to insert or if I wanted to update or delete. Basically, I need help in being able to use other commands besides SELECT.