丁丁 16:01:23 (多人发送)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class TestConnection {
private static String url = "jdbc:mysql://59.76.57.32:3306/mytest";
private static String username = "root";
private static String password = "root";
private static Connection conn =null;
private static Statement st = null;
private static ResultSet rs = null;
//为了限定对象的使用,所以讲构造方法私有化,那么,我可以对外只提供一个单独的实例对象
//单例模式--单独的一个实例的方法
private TestConnection() throws ClassNotFoundException, SQLException{ Class.forName("com.mysql.jdbc.Driver");
conn =DriverManager.getConnection(url,username,password);
}
public static Connection getConnection() throws SQLException, ClassNotFoundException{
new TestConnection();
return conn;
}
public static void main(String[] args){
//testBySelect();
testByInsert("叮当",25,"2011-3-11 15:50:33");
}
public static void testByInsert(String name,int age,String date){ String sql="insert into st(name,age,dateByTest) values('"+name+"',"+age+",'"+date+"')";
System.out.println(sql);
int flag = -1;
try {
conn = TestConnection.getConnection();
st = conn.createStatement();
flag =st.executeUpdate(sql);
if(flag>0){
System.out.println("insert操作成功");
}else{
System.out.println("insert操作失败");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
//6.关系所有对数据库的连接
try {
rs.close();
st.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void testBySelect(){
try {
conn = TestConnection.getConnection();
st= conn.createStatement();
String sql=" select id,avg(distinct age)as age from st group by id";
rs = st.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getInt("age")+" "+rs.getInt("id"));
}
}catch(SQLException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
//6.关系所有对数据库的连接
try {
rs.close();
st.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}。