使用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的數卜灶扒據庫埠號這個不用型昌改