[英]How to check Username is already exist in the database or not sql server
[英]How to check if username already exist in the sql database before one can create new account using java
當我想在用戶創建新帳戶或更新他/她的用戶名時提示消息並且sql數據庫中已存在該用戶名時,我如何輸入代碼。 當我在CreateNewUserAccount類上單擊“保存”按鈕時,這是我的代碼的一部分:
String sql = "insert into tblUserInfo (UserID, LastName, FirstName, PositionID, Username, Password) values(?, ?, ?, ?, ?, ?) " ;
try{
pst = conn.prepareStatement(sql);
pst.setString(1, txtUserID.getText());
pst.setString(2, txtLastName.getText());
pst.setString(3, txtFirstName.getText());
pst.setString(4, (String) comboPosition.getSelectedItem().toString().substring(0, 1));
pst.setString(5, txtUsername.getText());
pst.setString(6, txtPassword.getText());
pst.execute();
if(txtConfirmPassword.getText().equals(txtPassword.getText())){
JOptionPane.showMessageDialog(null, "Saved New User Account");
clear();
}
else{
JOptionPane.showMessageDialog(null, "Incompatible Password");
txtConfirmPassword.setText("");
}
//UpdateEmployeeTable();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
以及我的UserAccount類,用戶可以在其中更新/編輯他們的信息,包括用戶名:
String sql = "update tblUserInfo set LastName = ?, FirstName = ?, PositionID = ?, Username = ?, Password = ? where UserID= ?";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, txtLastName.getText());
pst.setString(2, txtFirstName.getText());
pst.setString(3, (String) comboPos.getSelectedItem().toString().substring(0, 1));
pst.setString(4, txtUserName.getText());
pst.setString(5, txtPassword.getText());
pst.setString(6, txtUserID.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "User Account Updated");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
我怎么能對此進行檢查? 提前致謝
我會用這樣的東西
IF EXISTS (SELECT * FROM Table1 WHERE Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
INSERT INTO Table1 VALUES (...)
http://blogs.msdn.com/b/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx
一種選擇是對用戶名不相同的用戶名進行計數查詢,例如:
select count(Username) from tblUserInfo where UserId != ?
如果您發現結果大於零,則該用戶ID由其他人使用,則顯示警告。
你可以這樣做
Statement st=con.getConnection(.....);
String query= "select username from tables where username="uservalue"";
ResultSet rs=st.executeQuery(query);
int value=0;
while(rs.next())
{
value++;
}
if(value>1)
{
String query= "select username from tables where username="uservalue"";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
String user=rs.getString("username");
}
String updatequery="update tables set username="updatevalue" where username="updatevalue"";
int q=st.executeupdate(updatequery);
}
else
{
insert query..........
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.