代码:
DButil.java
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.Connection;
public class DButil {
/*
* 打开数据库
*/
private static String driver;//连接数据库的驱动
private static String url;
private static String username;
private static String password;
static {
driver="com.mysql.jdbc.Driver";//需要的数据库驱动
url="jdbc:mysql://localhost:3306/test";//数据库名路径
username="root";
password="root";
}
public static Connection open()
{
try {
Class.forName(driver);
return (Connection) DriverManager.getConnection(url,username, password);
} catch (Exception e) {
System.out.println("数据库连接失败!");
// TODO Auto-generated catch block
e.printStackTrace();
}//加载驱动
return null;
}
/*
* 关闭数据库
*/
public static void close(Connection conn)
{
if(conn!=null)
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Tesgt.java
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.CallableStatement;
import com.mysql.jdbc.Connection;
public class Tesgt {
public static void main(String[] args) {
// TODO Auto-generated method stub
test2();
}
static void test1()
{
Connection conn=DButil.open();
try {
CallableStatement cstmt=(CallableStatement) conn.prepareCall("{call all_customers()}");//查询存贮过程
ResultSet rs=cstmt.executeQuery();
while(rs.next())
{
int id=rs.getInt(1);
String name=rs.getString(2);
String email=rs.getString(3);
System.out.println(id+","+name+","+email);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void test2()
{
Connection conn=DButil.open();
try {
CallableStatement cstmt=(CallableStatement) conn.prepareCall("{call insert_customers(?,?)}");//查询插入数据的存贮过程
cstmt.setString(1,"haige");
cstmt.setString(2,"8512@qq.com");
int r=cstmt.executeUpdate();
System.out.println(r);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}