java的数据库连接
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class sql {
// 连接方法连接数据库成功后返回Statement对象用来执行SQL语句
// lianjie方法需要一个数据库名作为参数
public Statement lianjie(String sqlName) {
//注册数据库的驱动
try {
Class.forName(“com.mysql.jdbc.Driver”);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.print(“数据库注册失败!”);
e.printStackTrace();
}
//创建一系列的对象
Connection conn = null;
Statement stat = null;
String url = “jdbc:mysql://localhost:3306/” + sqlName;
String username = “root”;
String password = “rootroot”;
//连接数据库,将连接对象赋给Connectiond对象 conn
try {
conn = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.print(“数据库连接失败!”);
e.printStackTrace();
}
//通过Commection对象 conn 的createStatement()方法获取Statement对象
try {
stat = conn.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.print(“Statement对象获取失败!”);
e.printStackTrace();
}
return stat;
}
}
//lianjie(String sqlName) 方法返回的是一个Statement对象
Statement对象可以使用execute(“sql语句”)方法来执行sql语句,用ResultSet对象去接收返回结果