使用JDBC进行数据库的增删改查操作1.下载Microsoft SQL Server 2005 JDBC 驱动包jar文件 将jar文件引入工程中2.封装数据库链接的获取和关闭操作import java.sql.*;public class BaseDao {x0dx0a /**x0dx0a * 数据库驱动类的字符串,完整的包名加类名 在工程中查看添加的jar文件 能看到这个类x0dx0a */x0dx0a private static final String DRIVE = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; /**x0dx0a * 数据库连接地址x0dx0a * x0dx0a * DataBaseName=数据库名称 其它固定x0dx0a */x0dx0a private static final String URL = "jdbc:sqlserver://localhost:1433;DataBaseName=bbs"; /**x0dx0a * 连接数据库的用户名x0dx0a */x0dx0a private static final String USER = "sa"; /**x0dx0a * 用户密码x0dx0a */x0dx0a private static final String PASSword = ""; /**x0dx0a * 获取连接 异常直接抛出 或者捕获后自定义异常信息再抛出x0dx0a */x0dx0a public static Connection getConnection() throws Exception {x0dx0a Class.forName(DRIVE);x0dx0a return DriverManager.getConnection(URL, USER, PASSWORD);x0dx0a } /**x0dx0a * 关闭与数据库的连接 释放资源x0dx0a */x0dx0a public static void closeAll(ResultSet resultSet, PreparedStatement pst,x0dx0a Connection connection) throws Exception {x0dx0a if (resultSet != null)x0dx0a resultSet.close();x0dx0a if (pst != null)x0dx0a pst.close();x0dx0a if (connection != null)x0dx0a connection.close();x0dx0a }}3.创建图书的实体类public class Book {x0dx0a /**x0dx0a * 数据库主键x0dx0a */x0dx0a private Long id; /**x0dx0a * 作者x0dx0a */x0dx0a private String author; /**x0dx0a * 书名x0dx0a */x0dx0a private String name;x0dx0a /**x0dx0a * 默认构造x0dx0a *x0dx0a */x0dx0a public Book() {x0dx0a }x0dx0a /**x0dx0a * 全字段构造x0dx0a * @param idx0dx0a * @param authorx0dx0a * @param namex0dx0a */x0dx0a public Book(Long id, String author, String name) {x0dx0a this.id = id;x0dx0a this.author = author;x0dx0a this.name = name;x0dx0a }x0dx0a /**x0dx0a * 以下为读写属性的方法x0dx0a * @returnx0dx0a */x0dx0a public String getAuthor() {x0dx0a return author;x0dx0a }x0dx0a public void setAuthor(String author) {x0dx0a this.author = author;x0dx0a }x0dx0a public Long getId() {x0dx0a return id;x0dx0a }x0dx0a public void setId(Long id) {x0dx0a this.id = id;x0dx0a }x0dx0a public String getName() {x0dx0a return name;x0dx0a }x0dx0a public void setName(String name) {x0dx0a this.name = name;x0dx0a }x0dx0a}x0dx0a4.创建与图书表交互的工具类import java.sql.Connection;x0dx0aimport java.sql.PreparedStatement;x0dx0aimport java.sql.ResultSet;x0dx0aimport java.util.ArrayList;x0dx0aimport java.util.List;public class BookDao {x0dx0a /**x0dx0a * 添加新书x0dx0a * x0dx0a * @param book 要添加入数据库的图书 作者 书名 必须给定x0dx0a */x0dx0a public void addBook(Book book) throws Exception {x0dx0a // 连接x0dx0a Connection connection = null;x0dx0a // 执行语句x0dx0a PreparedStatement pst = null;x0dx0a try {x0dx0a connection = BaseDao.getConnection();x0dx0a // 构造执行语句x0dx0a String sql = "insert into book values(" + book.getAuthor() + ","x0dx0a + book.getName() + ")";x0dx0a pst = connection.prepareStatement(sql);x0dx0a pst.executeUpdate(); } catch (Exception e) {x0dx0a // 抛出异常x0dx0a throw e;x0dx0a } finally {x0dx0a // 无论是否异常 均关闭数据库x0dx0a BaseDao.closeAll(null, pst, connection);x0dx0a }x0dx0a } /**x0dx0a * 查询所有书籍列表x0dx0a */x0dx0a public List
② 求一个简单又经典的JAVA数据库连接的例子,要有源代码哦!
我就弄的用户登入的代码吧.这个挺简单的.
这是题目:
用户登陆验证:
1.创建数据库Test,并新建用户表users
字段包含:username varchar(20) not null
userpwd varchar(20) not null
在JBUILDER中编写Long类,实现登陆界面,并在用户输入用户名和密码后,
完成按纽的单击事件,对用户输入的数据进行验证,
(需要严整数据是否为空,密码长度必须是15位),
并实现与数据库的连接,将用户输入的用户名密码与表中的记录比较,
若用户名正确且密码正确,弹出提示框告知登陆成功,否则登陆失败。
这是代码:
//连接数据库
boolean isLogin(String name,String pwd){
boolean flag=false;
Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;
//加载驱动
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
//连接数据库
try {
conn=DriverManager.getConnection("jdbc:odbc:login");
String sql="select * from [user] where username=? and userpwd=?";
pst=conn.prepareStatement(sql);
pst.setString(1,name);
pst.setString(2,pwd);
rs=pst.executeQuery();
if(rs.next())
flag=true;
} catch (Exception ex) {
ex.printStackTrace();
}finally{
try {
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return flag;
}
//验证方法
public void jButton1_actionPerformed(ActionEvent e) {
String name=jTextField1.getText();
String pwd=jTextField2.getText();
//错误处理
if(name.equals("")||pwd.equals(""))
JOptionPane.showMessageDialog(this,"请输入完整的信息");
else {
if(isLogin(name,pwd))
JOptionPane.showMessageDialog(this,"登陆成功");
else
JOptionPane.showMessageDialog(this,"用户名或密码错误");
}
}
}
.....
.....
这是在事件里写的,
③ 求Java 注册登录 连接到数据库的源代码。
package cc.icoc.javaxu.;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class MySQLOprea { /** * 增加记录 INSERT INTO 表名(字段名,字段名) VALUES (值,值); * 删除记录 DELETE FROM 表名 WHERE 条件() * 修改记录 UPDATE 表名 SET 字段=值,字段=值 WHERE 条件 * 查询记录 SELECT 字段,字段 FROM 表名 WHERE 条件 */ ResultSet rs = null; Connection conn = null; Statement statement = null; //链接 public Connection connSQL() { String DRIVER = "com.mysql.jdbc.Driver";// 数据库驱动 String URL = "jdbc:mysql://localhost:3306/mydata?useUnicode=true&characterEncoding=gb2312";// String DBNAME = "root";// 用户名 String DBPASS = "341341";// 密码 try { Class.forName(DRIVER).newInstance();// 注册驱动 conn = DriverManager.getConnection(URL, DBNAME, DBPASS); statement = conn.createStatement(); } catch (Exception e) {} return conn; } //增 /** * 插入新记录的操作 * @param table 表名 * @param userName 插入的用户名 * @param passWord 插入的用户密码 * @return true代表插入成功,false代表插入失败 */ public String insert(String table, String userName, String passWord) { connSQL(); String s = "注册成功"; try { String insert = "insert into "+table+"(userName,passWord) values ("+"'"+userName+"'"+","+"'"+passWord+"'"+")"; statement.executeUpdate(insert); closeDB(); } catch (Exception e) { // TODO: handle exception s = "注册失败"+e.toString(); } return s; } //删 public void delete(String table, String whereValue) throws SQLException { String delete = "Delete from "+table+" where userName = "+whereValue; statement.executeUpdate(delete); } //改 public void update(String table, String whereValue , String newValue) throws SQLException { String update = "Update "+table+" set passWord ="+newValue+" where userName ="+whereValue; statement.executeUpdate(update); } //查 public String query(String table , String whereValue1 ,String whereValue2, String whatCol1, String whatCol2) throws SQLException { connSQL(); String query = null;// ResultSet set= null; try { query = "select "+whatCol1+","+whatCol2+" from "+table +" where "+whatCol1+"="+'"'+whereValue1+'"'+" and "+whatCol2+"="+'"'+whereValue2+'"'; rs = statement.executeQuery(query); closeDB(); } catch (Exception e) { // TODO: handle exception return "false exception:"+e.toString(); } if(rs.next()) { return "true:"; } return "false:"; } private void closeDB() { // TODO Auto-generated method stub try { if(rs != null) { rs.close(); } if(statement != null) { statement.close(); } if(conn != null) { conn.close(); } } catch (Exception e) { // TODO: handle exception System.out.println("数据库关闭时出现异常"); } }}
④ java里如何输写连接数据库的语句
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.sql.*;
import java.util.PropertyResourceBundle;
public class MySqlConnector {
/*
* 先在bin目录下新建一个dbCon.ini文件,连的是mysql
* 内容 如下:
* userName=你的数据库用户名
* password=你的数据库用户密码
* database=要连接的数据库名称
*/
private static final String CON_NAME = "userName";
private static final String CON_PASS = "password";
private static final String CON_DNAME = "databaseName";
private Connection connection = null;
private MySqlConnector() {
}
public static MySqlConnector getInstance() {
return new MySqlConnector();
}
private boolean dataInit() {
boolean isOK = false;
String userName = "";
String password = "";
String databaseName = "";
PropertyResourceBundle rBoundle = null;
try {
String conPath = MySqlConnector.class.getResource("/").toString() + "/dbCon.ini";
URI uri = new URI(conPath);
File file = new File(uri);
rBoundle = new PropertyResourceBundle(new FileInputStream(file));
userName = rBoundle.getString(MySqlConnector.CON_NAME);
password = rBoundle.getString(MySqlConnector.CON_PASS);
databaseName = rBoundle.getString(MySqlConnector.CON_DNAME);
String url;
url = "jdbc:mysql://localhost/" + databaseName + "?user="
+ userName + "&password=" + password;
System.out.println(url);
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url);
isOK = true;
} catch (Exception e) {
e.printStackTrace();
isOK = false;
}
return isOK;
}
public Connection getConnection() {
if (dataInit()) {
return connection;
} else {
return null;
}
}
public void close() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
⑤ java和数据库连接,实现登录功能
根据输入的用户名来查找出这个用户名对于的密码,再把这个密码和输入的密码进行比较,看看是不是一样的。
sql="=?";
Connecttionconn=....
PreparedStatementps=conn.conn.prepareStatement(sql);
ps.setString(1,userName);//这个用户名是用户输入的
privateResultSetrs=ps.executeQuery();
while(rs.next()){
Stringpassword=rs.getString("password");//这个密码是数据库里面存的密码,然后你拿这个和输入的对比就可以了
}
⑥ java连接数据库的代码
package mysql;
import java.sql.*;
/**
* @author xys
*/
public class ConnectMysql {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306/databaseName";
String user = "mysqluser";
String password = "password";
String driverClass = "com.mysql.cj.jdbc.Driver";
Connection connection = null;
Class.forName(driverClass);
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null) {
System.out.println("数据库连接成功");
} else {
System.out.println("数据库连接失败");
connection.close();
}
return connection;
}
public void getResult() throws ClassNotFoundException, SQLException {
// 实例化 Statement 对象
Statement statement = getConnection().createStatement();
// 要执行的 Mysql 数据库操作语句(增、删、改、查)
String sql = "";
// 展开结果集数据库
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
// 通过字段检索
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// 输出数据
System.out.println("ID : " +id);
System.out.println("name :" + name);
}
// 完成后需要依次关闭
resultSet.close();
statement.close();
getConnection().close();
}
}
⑦ 求用Java实现程序注册和登陆并且连接MySQL数据库
假设登陆Oracle的数据库,连接方式
String driver = "oracle.jdbc.OracleDriver";
Connection cn = null;
Class.forName(driver);
String url = "jdbc:oracle:thin:@localhost:1521:ORACLE";
String user = "system";
String pwd = "密码";
cn = DriverManager.getConnection(url,user,pwd);
Statement st = cn.createStatement();
String sql = "Insert into loginfo (id,username,user,type) values( "id="+你的id+"username="+user+",password="+pwd+",type="+你辩烂的type);
st.executeUpdate(sql);
st.closed;
cn.closed;
Mysql Database
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/数据库名称",
"账户","密码");
localhost你的ip地址
3306 mysql的数卜灶扒据库端口号这个不用型昌改