CST363: Introduction to Database, Week 6
What We Learned This Week:
This week we learned how to use Java and MySQL together through Connector/J. JDBC allows Java programs to communicate with relational databases using standard classes and methods from the java.sql package. To start, a program must first connect to the database: DriverManager.getConnection(). Since connections can fail if the login info or database path is incorrect, create them in a try-catch block and close them when finished with connection.close().
Once connected, queries are executed using the Statement interface. The executeQuery() method runs SELECT statements and returns a ResultSet that holds the results. executeUpdate() handles changes like INSERT, UPDATE, or DELETE, while execute() can run general SQL commands. To access the data, the ResultSet acts like a cursor that moves through each row using next(). Individual column values can then be retrieved with methods like getInt(), getDouble(), or getString().
The PreparedStatement interface makes queries safer and more efficient by allowing parameters in SQL statements using ? placeholders. Methods like setString() or setInt() assign actual values to these placeholders, which also helps prevent SQL injection attacks.
CallableStatement interface is used for calling stored procedures in MySQL. It allows you to send data into procedures with setInt() or setString() and retrieve results with registerOutParameter().

Comments
Post a Comment