#Adding column name as a value in to a query in jdbc connection (javalin)
1 messages ยท Page 1 of 1 (latest)
Here is an AI assisted attempt to answer your question ๐ค. Maybe it helps! In any case, a human is on the way ๐. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
import io.javalin.Javalin;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class JDBCTest {
public static void main(String[] args) {
Javalin app = Javalin.create().start(7000);
// Create a route to handle queries
app.get("/query/:columnName", ctx -> {
String columnName = ctx.pathParam("columnName");
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
String query = "SELECT " + columnName + " FROM mytable";
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
System.out.println(rs.getString(columnName));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
In this code snippet, we are using Javalin to create a simple web server that listens for GET requests on the "/query/:columnName" endpoint. The endpoint expects a path parameter called "columnName" which will be used in the SQL query to retrieve data from a MySQL database.
We establish a JDBC connection to the database, construct a SQL query dynamically by including the column name provided in the path parameter, and execute the query using a prepared statement. We then loop through the result set to print out the values of the specified column.
This code demonstrates how you can add a column name as a value in a query when working with JDBC connections in Java, specifically within the context of a Javalin web server.