/*
* 简单的通过mysql来插入、查询数据
* 以下是插入部分:
*/
package servlet;
import java.sql.*;
public class TestInsert {
public static void main(String[] args) {
Connection cn=null;
Statement stmt=null;
try {
Class.forName("com.mysql.jdbc.Driver");//加载MySQL驱动程序
//建立与数据库的连接
String url = "jdbc:mysql://localhost:3306/training";
String user = "root";
String password = "ricky";
cn = DriverManager.getConnection(url,user,password);
stmt = cn.createStatement();//创建Statement对象
//不管是insert,delete,update都是用这个executeUpdate来做。
stmt.executeUpdate("insert into team (name,slogan,leader) values ('酷毅团队','脚踏实地,共同提高','黄高武')");//向数据库增加数据
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
stmt.close();
cn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
/*
* 以下是数据查询部分:↓
*/
package servlet;
import java.sql.*;
public class TestQuery {
public static void main(String[] args) {
Connection cn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");//加载MySQL驱动程序
//建立与数据库的连接
String url = "jdbc:mysql://localhost:3306/training";
String user = "root";
String password = "ricky";
cn = DriverManager.getConnection(url,user,password);
stmt = cn.createStatement();//创建Statement对象
rs = stmt.executeQuery("select * from team");//执行查询
//把结果集里的数据显示出来
while(rs.next()) {
System.out.print(rs.getInt("id") + "\t");
System.out.print(rs.getString("name") + "\t");
System.out.print(rs.getString("slogan") + "\t");
System.out.println(rs.getString("leader"));
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
rs.close();
stmt.close();
cn.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}