Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Hibernate Basics Data Persistence & ORMs Using JDBC to Connect to a Database

Ly Nguyen
Ly Nguyen
8,749 Points

How do you create a statement and execute a query using Java and SQL?

I believe I am following the right steps but the compiler says that it cannot find the symbol.

Application.java
// Load class "org.sqlite.JDBC"

// Establish connection to database named "treehouse.db"
try(Connection c = DriverManager.getConnection("jdbc:sqlite:treehouse.db")) {
  Class.forName("org.sqlite.JDBC");
  Statement stmt = null;
  stmt = c.createStatement();
  ResultSet rs = stmt.executeQuery("INSERT INTO languages (id, name) VALUES (2, 'Java')");
} catch(SQLException ex) {

}
Ly Nguyen
Ly Nguyen
8,749 Points

I was able to figure out my mistake. I should have run the executeUpdate method instead of executeQuery method. Also, there is no ResultSet created if you're not querying.

New code that passes:

// Load class "org.sqlite.JDBC"

// Establish connection to database named "treehouse.db"
try(Connection c = DriverManager.getConnection("jdbc:sqlite:treehouse.db")) {
  Class.forName("org.sqlite.JDBC");
  Statement stmt = c.createStatement();
  stmt.executeUpdate("INSERT INTO languages (id, name) VALUES (2, 'Java')");
} catch(SQLException ex) {

}