package sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import domain.Person;
public class JdbcUtils {
// 表示定义数据库的用户名
private final String USERNAME = "root";
// 定义数据库的密码
private final String PASSWORD = "admin";
// 定义数据库的驱动信息
private final String DRIVER = "com.mysql.jdbc.Driver";
// 定义访问数据库的地址
private final String URL = "jdbc:mysql://localhost:3306/taonansql";
// 定义数据库的链接
private static Connection connection;
private static Connection conn;
public JdbcUtils() {
try {
Class.forName(DRIVER);
System.out.println("注册驱动成功!!");
} catch (Exception e) {
// TODO: handle exception
}
}
// 定义获得数据库的链接
public Connection getConnection() {
try {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (Exception e) {
// TODO: handle exception
}
return connection;
}
/**
*作用实例化 Connection
* */
private static void lianjieSql() {
JdbcUtils JJ = new JdbcUtils();
conn = JJ.getConnection();
}
/**
* 作用:对数据进行查询 时间:二〇一六年三月二十六日 08:20:43 作者:康小岱
*
* */
public static List<Person> getlistPersonshuju() {
List<Person> list = new ArrayList<Person>();
PreparedStatement ps = null;
try {
// select * from table limit 7,100; //搜索记录行 8-100
// conn.prepareStatement("select * from product limit "+i+",7");
ps = conn.prepareStatement("select * from user");
ResultSet rs = null;
rs = ps.executeQuery();
while (rs.next()) {
Person person = new Person();
person.setUsername(rs.getString("username"));
person.setPassword(rs.getString("password"));
list.add(person);
}
rs.close();
ps.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
return list;
}
//对数据进行添加
private static void set_user_toSql(String username,String password ) {
// String name = "康小岱";
// String sex = "康小岱";
String sql = "insert into user (username,password) values ('" + username
+ "' ,'" + password + "')";
try {
Statement state = connection.createStatement();
int count = state.executeUpdate(sql);
if (count > 0) {
System.out.println("执行成功......");
}
state.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
lianjieSql();
// System.out.println(getlistPersonshuju().toString());
set_user_toSql();
}
}
javaWeb连接数据库
最新推荐文章于 2023-03-29 14:42:48 发布