Package com. Test. database;
Import java. SQL. connection;
Import java. SQL. drivermanager;
Import java. SQL. resultset;
Import java. SQL. sqlexception;
Import java. SQL. statement;
Import java. util. Logging. Logger;
Public class dbconnect {
Static connection conn = NULL;
Static statement ST = NULL;
Static resultset rs = NULL;
Public static connection getconnection () throws sqlexception {
Try {
Class. forname ("com. MySQL. JDBC. Driver ");
} Catch (classnotfoundexception e ){
Logger. getlogger (E. getmessage ());
}
Try {
Conn = drivermanager. getconnection (
"JDBC: mysql: // localhost: 3306/test", "root", "root ");
} Catch (sqlexception e ){
E. getmessage ();
If (Conn! = NULL ){
Conn. Close ();
}
}
Return conn;
}
Public static int getinsert (INT Sid, string sname, string sex)
Throws sqlexception {
Conn = getconnection ();
Int I = 0;
String SQL = "insert into student values (" + Sid + ", '" + sname + "', '" + sex
+ "')";
/*
* Pay attention to the details of the Error. If the SID is written as a string, an exception occurs during data insertion.
In this case, "the sequence number in the database is not set to auto-increment" is not applicable here.
*/
Try {
St = conn. createstatement ();
I = st.exe cuteupdate (SQL );
} Catch (exception e ){
If (Conn! = NULL)
Conn. Close ();
E. printstacktrace ();
}
Return I;
}
Public static string getselect () throws sqlexception {
Conn = getconnection ();
String SQL = "select * from student ";
Try {
St = conn. createstatement ();
Rs = st.exe cutequery (SQL );
While (Rs. Next ()){
Rs. getint ("Sid ");
Rs. getstring ("sname ");
Rs. getstring ("sex ");
System. Out. println (Rs. getint ("Sid") + ","
+ Rs. getstring ("sname") + "," + Rs. getstring ("sex "));
}
} Catch (sqlexception e ){
Rs. Close ();
If (Conn! = NULL)
Conn. Close ();
E. printstacktrace ();
}
Return NULL;
}
Public static int getupdate (INT Sid, string SNA, string SE)
Throws sqlexception {
Conn = getconnection ();
Int I = 0;
String SQL = "Update student set sname = '" + SNA + "', sex = '" + Se + "'";
SQL = SQL + "where Sid =" + Sid;
Try {
St = conn. createstatement ();
I = st.exe cuteupdate (SQL );
} Catch (exception e ){
If (Conn! = NULL)
Conn. Close ();
E. printstacktrace ();
}
Return I;
}
Public static void getdelete (INT Sid) throws exception {
Conn = getconnection ();
String SQL = "delete from student where Sid =" + Sid;
Conn.createstatement(cmd.exe cute (SQL );
If (Conn! = NULL)
Conn. Close ();
}
Public static void main (string ARGs []) throws exception {
Dbconnect. getconnection ();
// Dbconnect. getinsert (6, "werrr", "M ");
Dbconnect. getupdate (1, "1", "uii ");
Dbconnect. getselect ();
Dbconnect. getdelete (0 );
}
}