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)
{
}
}
}
}