How to connect to MySQL with JSP/JDBC?

<%@ page import="java.sql.*" %>
<%@ page import="com.mysql.jdbc.Driver" %>

<%!
// mysql driver
String driver = "com.mysql.jdbc.Driver";

// the "url" to our DB, the last part is the name of the DB
String url = "jdbc:mysql://localhost/DBname";

// the default DB username and password may be the same as your control panel login

String name = "Username";
String pass = "Password";

%>

<html>
<head>
<title>testServlet</title>
</head>
<body>
<p>Attempting to open JDBC connection to:... </p> <%=url%>
<%
try
{
// Test the DB connection by making an empty table
String tableStr = "CREATE.....table test (testid mediumint(8), name varchar(100))";
Class.forName( driver );

// initialize the Connection, with our DB info ...
Connection con = DriverManager.getConnection( url, name, pass );

Statement stat = con.createStatement();
%>
<p> executing: <%=tableStr%></p>
<%
stat.executeUpdate( tableStr );
%>
<p> success.... </p>

<%
// close connection
con.close();
}

catch (SQLException sqle)
{ out.println("<p> Error opening JDBC, cause:</p> <b> " + sqle + "</b>"); }

catch(ClassNotFoundException cnfe)
{ out.println("<p> Error opening JDBC, cause:</p> <b>" + cnfe + "</b>"); }

%>
</body>
</html>

  • 44 istifadəçi bunu faydalı hesab edir
Bu cavab sizə kömək etdi?

Uyğun məqalələr

Create MS Access DSNLess connection string

Many people have requested this so here it is: "DRIVER={Microsoft Access Driver...

Do you support ASP?

 Yes, we support ASP.

Do you support Cold Fusion?

We do not support or Cold Fusion on our shared hosting servers, however you are more than welcome...

Do you support Servlets/JSP on Windows Server?

Yes, we support Servlet/JSP on our Windows Server.

Enable Parent Paths in Plesk - Windows Server

Many scripts use a function called parent paths. If you are running one of these scripts and...