Connect to a mysql database with Java

xiaoxiao2021-03-06  73

Connect to a mysql database with Java

Download mysql-connector-java-3.0.15-ga.zip, and extract.

Copy all files under the mysql-connector-java-3.0.15-bin.jar and the lib directory (including jdbc2_0-stdext.jar and JTA-SPEC1_0_1.jar) to copy to the project myweb WebContent / Web -Inf / lib: Refreshing the Lib Directory for the MyWeb Project: Create a class MYDBCONNECTION.JAVA that gets the database connection: Add a static function to get the connection: / *** get the mysql database connection * @ return * @throws instantiationException * @throws IllegalAccessException * @throws ClassNotFoundException * @throws SQLException * / public static Connection getConnection () throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {String driver = "com.mysql.jdbc.Driver"; String database = "testdb"; String user = " zene; string password = "zengrizhang"; string url = "jdbc: mysql: // localhost /" data "? user =" user "& password =" password; class.forname (driver) .newinstance (); Connection conn = drivermanager.getConnection (URL); Return Conn;} Test connection is successful: public static void main (String [] args) {try {getConnection (); sys Tem.out.println ("successfully connected! ");} Catch (exception e) {system.out.println (" Connection failed! "); E.PrintStackTrace ();}}}}}}}}}}} Create Date 2004-10-20 ** Changing File Template * Window> Preferences> Java> Code Generation> Code and Note * / package myweb; import java.sql.connection; import java.sql.driverManager; import java.sql.sqlexception; / *** @Author administrator ** Changing the template for the generated type annotation is * Window> Preferences> Java> Code Generation> Code and Note * / Public Class MyDbConnection {/ ** * gets mysql database connection * @return * @Throws instantiationException * @

throws IllegalAccessException * @throws ClassNotFoundException * @throws SQLException * / public static Connection getConnection () throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {String driver = "com.mysql.jdbc.Driver"; String database = "testdb"; String user = "zeng"; string password = "zengrizhang"; string url = "jdbc: mysql: // localhost /" Database "? user =" user "& password =" password; class.forname (driver) .newinstance () Connection conn = drivermanager.getConnection (URL); Return Conn;} / ** * * / public mydbconnection () {Super (); // TODO automatically generates constructor stub} public static void main (String [] args) { Try {getConnection (); system.out.println ("Connection Success!");} catch (exception e) {system.out.println ("Connection failed!"); E.PrintStackTrace ();}}} runs, view the results: Connections to the Logon.java in the MyWeb project.

In the method DOPOST in class logon.java, add the code saved to the database: // The following code saves the username and password to the database Boolean Issuccess = false; string errorMessage = ""; connection conn = null; try {conn = mydbconnection .GetConnection (); string sql = "INSERT INTO Myuser (username, password) VALUES (?,?)"; prededStatement PSTMT = conn.preparestatement (SQL); pstmt.setstring (1, username); pstmt.setstring (2, Password); pstmt.executeUpdate (); // Execute success issuccess = true;} catch (exception e) {if (conn! = null) Try {conn.rollback ();} catch (sqlexception E1) {E1.PrintStackTrace );} E.PrintStackTrace (); // Execute the failure Issuccess = false; errorMessage = E.getMessage ();} finally {if (conn! = Null) Try {conn.close ();} catch (sqlexception E1) { E1.PrintStackTrace ();}} // Output Results IF (Issuccess) {System.out.Println ("successfully added users to the database.");} else {system.out.println ("Add user to the database failed.

Error staff should be: " errorMessage);} The full code package myweb; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; / *** @version 1.0 * @ author * / public class LogonServlet extends HttpServlet implements Servlet {/ *** @see javax.servlet.GenericServlet # void () * / public void init () throws ServletException {super.init ();} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding ( "GBK"); String username = request.getParameter ( "username"); String password = request.getParameter ( "password"); System.out.println ( " Username: " username); system. OUT.PRINTLN ("Password:" password); // The following code saves the username and password to the database Boolean Issuccess = false; string errorMessage = ""; connection conn = null; try {conn = mydbconnection.getConnection (); string sql = "insert into myuser (username, password) values ​​(,??)"; PreparedStatement pstmt = conn.prepareStatement (sql); pstmt.setString (1, username); pstmt.setString (2, password); pstmt.executeUpdate (); // Execute the success Issuccess = true;} catch (exception e) {if (conn! = Null) Try {conn.rollback ();

转载请注明原文地址:https://www.9cbs.com/read-91620.html

New Post(0)