1. Download the MySQL JDBC driver: for example, mysql-connector-java-5.1.12 (available on pudn );
2. Create the lib directory in the project in eclipse, copy the mysql-connector-java-5.1.12-bin-jar to this directory, and add the jar package as external jar to the project in the build path of the project;
3. Import java. SQL .*;
Import com. MySQL. JDBC. driver;
4. Test
Try {
Class. forname ("com. MySQL. JDBC. Driver ");
System. Out. println ("MySQL driver loaded successfully! ");
Connect = drivermanager. getconnection ("JDBC: mysql: // localhost: 6033/mslog", "root", "root ");
System. Out. println ("database connection successful! ");
Stmt = connect. createstatement ();/* ----- create a statement object to send an SQL statement to the database -----*/
}
Catch (exception e ){
System. Out. Print ("failed to load MySQL driver! ");
E. printstacktrace ();
Return;
}
5. Structure of SQL statements when insert contains Variables
String IPaddress = getipadress (linecontent );
String reqtime = getreqtime (linecontent );
String keyword = getkeyword (linecontent, "keyword = ");
// String pagenum = getpagenum (linecontent );
String sourcepage = getsourcepage (linecontent );
String hititem = gethititem (linecontent );
String hiturl = gethiturl (linecontent );
String type = GetType (linecontent );
If (type = NULL)
Type = "0 ";
String sqlstr = "insert into hit (IPaddress, reqtime, keyword, sourcepage, hititem, hiturl, type) values (" + "'" + IPaddress + "', "+" '"+ reqtime +"', "+" '"+ keyword +"', "+ sourcepage +", "+ hititem + ", "+" '"+ hiturl +"', "+ Type +") "; // 11, 'beijing', 'beijing ')";
// String sqlstr = "insert into hit (IPaddress, reqtime, keyword, sourcepage, hititem, hiturl, type) values ('2017. 218. 202.4.135 ', '2017-08-11 00:00:00', 'female net', 2011, 'HTTP: // 97.24644.com/', 1 )";
System. Out. println (sqlstr );
Insertdb (sqlstr );
/////////////
Private void insertdb (string sqlstr)
{
If (stmt! = NULL)
{
// Insert database records
Try {
Stmt.exe cuteupdate (sqlstr); //. executequery (sqlstr );
}
Catch (exception E)
{
System. Out. println ("insertion record failed:" + sqlstr );
E. printstacktrace ();
}
}
}