1.java連線資料庫
阿新 • • 發佈:2018-12-11
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
public class connection {
/*
* mysql> create table custom(
-> id int primary key auto_increment,
-> uname varchar(16) not null,
-> upass varchar(16) not null
-> );
*/
public void login(String username,String userpassword) throws ClassNotFoundException, SQLException{
// 1.註冊驅動
Class.forName("com.mysql.jdbc.Driver");
// 2.得到連線
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/eclipse_database", "root", "123456");
// 3.編寫sql語句(使用佔位符而不使用字元拼接)
String sql="select * from customer where uname=? and upass=? ";
// 4.建立預處理物件
PreparedStatement preparedStatement=connection.prepareStatement(sql);
// 5.給sql語句中的佔位符設定引數
preparedStatement.setString(1, username);
preparedStatement.setString(2, userpassword);
// 6.執行查詢操作
ResultSet rSet=preparedStatement. executeQuery();
// 7.對結果集進行處理
if (rSet.next()) {
System.out.println("恭喜您," + username + ",登入成功!");
System.out.println(sql);
} else {
System.out.println("賬號或密碼錯誤!");
}
if (rSet!=null) {
rSet.close();
}
if (preparedStatement!=null) {
preparedStatement.close();
}
if (connection!=null) {
connection.close();
}
}
@Test
public void testLogin() throws ClassNotFoundException, SQLException{
login("老王","123456");
}
}