建立与mysql的连接必须要引入 sqlconnect包
此类的用途在于打开和关闭数据库
package linklist;//包名
import java.sql.Connection; //connect包
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DBhelper {
public static final String url = "jdbc:mysql://127.0.0.1/text"; //连接本地mysql里面的text数据库
public static final String name = "com.mysql.jdbc.Driver"; //利用DriverManger里面的Driber类建立桥接器
public static final String user = "root"; //确定要进入的mysql用户
public static final String password = "12345678"; //用户密码
public Connection conn = null;
public PreparedStatement pst = null;
public DBhelper(String sql) {
try {
Class.forName(name); //指定连接类型
conn = DriverManager.getConnection(url,user,password); //获取连接;
pst = conn.prepareStatement(sql); //准备执行语句
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
this.conn.close();
this.pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package linklist;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.omg.CORBA.SystemException;
public class Demo {
static String sql = null; //创建sql语句对象
static DBhelper db1 = null; //建立DBHelper对象
static ResultSet ret = null; //建立语句回复对象
public static void main(String[] args) {
sql = "select*from test"; //sql语句;
db1 = new DBhelper(sql); //创建DBHelper对象;
try {
ret = db1.pst.executeQuery(); //执行语句,得到结果集
while (ret.next()) {
String uid = ret.getString(1); //第一列
String ufname = ret.getString(2); //第二列
String ulname = ret.getString(3); //第三列
System.out.println(uid +"\t" + ufname + "\t" + ulname ); //打印得到的表的内容
}//显示数据
ret.close(); //关闭连接
db1.close(); //关闭与DBHlper的关联
} catch (SQLException e) {
e.printStackTrace();
}
}
}
转载于http://www.cnblogs.com/GarfieldEr007/p/5746134.html