Code for connecting to the MYSQL database through Java

Source: Internet
Author: User

The Java database connection has finally been completed. Although the function is simple, I will introduce a more complex program. In the future, most database operations can be completed with just a mouse, this time, the database still uses the same Mysql web_data database as the very small database management system (JSP.

The figure is as follows:



The Code is as follows:
------------------------------------------------------------

Import java. SQL .*;
Import javax. swing .*;
Import java. awt .*;
Import java. awt. event .*;
Import java. util .*;

Public class inensshow extends JFrame {


Private Connection connection;
Private Statement statement;
Private ResultSet resultSet;
Private ResultSetMetaData rsMetaData;

// GUI variable definition
Private JTable table;
Private JTextArea inputQuery;
Private JButton submitQuery;

Public inensshow ()
{
// Form title
Super ("Enter the SQL statement and press the query button to view the result. ");

String url = "jdbc: mysql: // localhost: 3306/web ";
String username = "inens ";
String password = "inens ";
// Load the driver to connect to the database
Try {
Class. forName ("org. gjt. mm. mysql. Driver ");
Connection = DriverManager. getConnection (
Url, username, password );
}
// Catch exceptions in the driver Loading
Catch (ClassNotFoundException cnfex ){
System. err. println (
"Failed to load the JDBC/ODBC driver. ");
Cnfex. printStackTrace ();
System. exit (1); // terminate program
}
// Catch database connection exceptions
Catch (SQLException sqlex ){
System. err. println ("unable to connect to Database ");
Sqlex. printStackTrace ();
System. exit (1); // terminate program
}
// If the database connection is successful, a GUI is created.
// SQL statement
String test = "SELECT * FROM data ";
InputQuery = new JTextArea (test, 4, 30 );
SubmitQuery = new JButton ("query ");
// Button event
SubmitQuery. addActionListener (
New ActionListener (){
Public void actionreceivmed (ActionEvent e)
{
GetTable ();
}
}
);

JPanel topPanel = new JPanel ();
TopPanel. setLayout (new BorderLayout ());
// Enter the "input query" edit box to "CENTER"
TopPanel. add (new JScrollPane (inputQuery), BorderLayout. CENTER );
// Set the "Submit query" button to "SOUTH"
TopPanel. add (submitQuery, BorderLayout. SOUTH );
Table = new JTable ();
Container c = getContentPane ();
C. setLayout (new BorderLayout ());
// Set the "topPanel" edit box to "NORTH"
C. add (topPanel, BorderLayout. NORTH );
// Set the "table" edit box to "CENTER"
C. add (table, BorderLayout. CENTER );
GetTable ();
SetSize (500,300 );
// Display Form
Show ();
}

Private void getTable ()
{
Try {
// Execute the SQL statement
String query = inputQuery. getText ();
Statement = connection. createStatement ();
ResultSet = statement.exe cuteQuery (query );
// Display the query results in the table
DisplayResultSet (resultSet );
}
Catch (SQLException sqlex ){
Sqlex. printStackTrace ();
}
}

Private void displayResultSet (ResultSet rs)
Throws SQLException
{
// Locate the first record
Boolean moreRecords = rs. next ();
// If no record exists, a message is prompted.
If (! MoreRecords ){
JOptionPane. showMessageDialog (this,
"No records in the result set ");
SetTitle ("no record display ");
Return;
}
Vector columnHeads = new Vector ();
Vector rows = new Vector ();
Try {
// Obtain the field name
ResultSetMetaData rsmd = rs. getMetaData ();
For (int I = 1; I <= rsmd. getColumnCount (); ++ I)
ColumnHeads. addElement (rsmd. getColumnName (I ));
// Obtain the record set
Do {
Rows. addElement (getNextRow (rs, rsmd ));
} While (rs. next ());
// Display the query results in the table
Table = new JTable (rows, columnHeads );
JScrollPane scroroller = new JScrollPane (table );
Container c = getContentPane ();
C. remove (1 );
C. add (scroller, BorderLayout. CENTER );
// Refresh the Table
C. validate ();
}
Catch (SQLException sqlex ){
Sqlex. printStackTrace ();
}
}


Private Vector getNextRow (ResultSet rs,
ResultSetMetaData rsmd)
Throws SQLException
{
Vector currentRow = new Vector ();
For (int I = 1; I <= rsmd. getColumnCount (); ++ I)
CurrentRow. addElement (rs. getString (I ));
// Return a record
Return currentRow;
}

Public void shutDown ()
{
Try {
// Disconnect the database
Connection. close ();
}
Catch (SQLException sqlex ){
System. err. println ("Unable to disconnect ");
Sqlex. printStackTrace ();
}
}

Public static void main (String args [])
{
Final inensshow app =
New inensshow ();
App. addWindowListener (
New WindowAdapter (){
Public void windowClosing (WindowEvent e)
{
App. shutDown ();
System. exit (0 );
}
}
);
}
}


------------------------------------------------------------

This time in WIN98 is hard to make. Because the Mysql driver has not been added to CLASSPATH, but JSP can be used. (For details about how to load the 98 driver of JSP, refer to the error message about the connection between Jsp and Mysql ), so this time I tested it in XPServer.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.