CS157a
Chris Pollett
Nov 25, 2019
CREATE DATABASE test;
CREATE TABLE my_table ( a INT, b VARCHAR(20) ); INSERT INTO my_table VALUES (1, "hi"), (2, "bye"), (3, "yo");
import java.sql.*; class JdbcTest { public static void main(String[] args) { Connection conn = null; ResultSet rs = null; Statement stmt = null; try { conn = DriverManager.getConnection( "jdbc:mysql://localhost/test?" + "user=root&password=root"); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM my_table"); while (rs.next()) { int a = rs.getInt("a"); String b = rs.getString("b"); System.out.println("a:" + a + "\tb:" + b); } } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { } // ignore rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException sqlEx) { } // ignore stmt = null; } } } }
conn = DriverManager.getConnection( jdbc:mysql://localhost/test?" + "user=root&password=root");
javac JdbcTest.java
java -cp .:/Users/cpollett/Desktop/mysql-connector-java-8.0.18.jar JdbcTest
a:1 b:hi a:2 b:bye a:3 b:yo
Which of the following is true?
INSERT INTO Studio(name) SELECT DISTINCT studioName FROM Movies WHERE studioName NOT IN (SELECT name FROM Studio);
int a=5; rs = stmt.executeQuery("SELECT * FROM my_table WHERE a=" + a);This is called an ad hoc query and is both dangerous from a security point of view and will tend to be slow.
PreparedStatement pstmt = conn.prepareStatement ("select * from EMPLOYEE where fname=? and salary=?"); pstmt.setString(1,"bob"); pstmt.setInt(2, 123); ResultSet rs = pstmt.executeQuery();
String ssn = "123456789"; stmt.executeUpdate("DELETE FROM EMPLOYEE WHERE SSN="+ssn);(we could have used a prepared statement).