Eclipse JDBC MySQL

Source: Internet
Author: User
Import java. SQL .*;

Public class jdbchelloworld
{
Public static void main (string [] ARGs)
{// 1. register the driver
Try {
Class. forname ("com. MySQL. JDBC. Driver ");
}
Catch (classnotfoundexception e ){
E. printstacktrace ();
} // MySQL driver
// Define variables first, and then use and disable
Connection conn = NULL; // database connection
Statement stmt = NULL; // database expression resultset rs = NULL; // result set
Resultset rs = NULL;
Try {
// 2. Obtain the database connection
Conn = java. SQL. drivermanager. getconnection ("JDBC: mysql: // localhost: 3306/test? Useunicode = true & characterencoding = GBK "," root ", null); // the root user name is blank
// 3. Get the expression
Stmt = conn. createstatement ();
// Execute the SQL statement for inserting data
Int ROW = stmt.exe cuteupdate ("insert into student (username, password, age) values ('zhang san', '123', 20 )");
System. Out. println ("inserted" + row );
// 4. Execute SQL
Rs = stmt.exe cutequery ("select * from student ");
// 5. display the data in the result set
While (Rs. Next ())
{
System. Out. println ("No. =" + Rs. getint (1 ));
System. Out. println ("Student name =" + Rs. getstring ("username "));
System. Out. println ("Password =" + Rs. getstring ("password "));
System. Out. println ("age =" + Rs. getstring ("Age "));
}
// Execute the SQL statement for deleting data. The ID of the deleted record is 7.
Row = stmt.exe cuteupdate ("delete from student where id = 7 ");
System. Out. println ("deleted" + row );
}
Catch (sqlexception E)
{
E. printstacktrace ();
} Finally
{
// 6. Release the resource. We recommend that you put it in the finally statement to ensure that all resources are disabled.
Try
{
Rs. Close ();
} Catch (sqlexception E)
{
}
Try
{
Stmt. Close ();
} Catch (sqlexception E)
{
}
Try {
Conn. Close ();
} Catch (sqlexception E)
{
}
}
}
}

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.