How to Connect to MySQL in JSP
Posted on In ProgrammingWe use tomcat as the container used for instructions in the post.
1) Download the driver mysql-connector-java-*.*.*-bin.jar and put it into WEB-INF/lib/, and remember to restart tomcat.
2) The example code as follows.
String driverName="com.mysql.jdbc.Driver";
String userName="username";
String userPasswd="password";
String dbName="dbname";
String tableName="tablename";
String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn=DriverManager.getConnection(url);
Statement statement = conn.createStatement();
String sql="SELECT * FROM "+tableName;
ResultSet rs = statement.executeQuery(sql);
// get the result
ResultSetMetaData rmeta = rs.getMetaData();
// the the number of columns
int numColumns=rmeta.getColumnCount();
// out each field
while(rs.next()) {
out.print(rs.getString(1)+" ");
out.print("|");
out.print(rs.getString(2));
out.print("
");
}
out.print("
");
out.print("Operations on the DB is done.");
rs.close();
statement.close();
conn.close();