Hi I'm developing app for a school project and I want need to create a user which will be saved in the database.
I've created a Profile class
public class Profile{
private String username;
private String password;
public Profile(String _username, String _password){
this.username = _username;
this.password = _password;
}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return this.username;
}
public void setPassword(String _password){
this.password = _password;
}
public String getPassword(){
return this.password;
}
Than I have created a DBConnect class which will contain all the methods one of them being CreateProfile which I want to user to Insert the values for new profile into the database "user" table.
public class DBConnect {
private Connection dbConnection;
public DBConnect(){
try{
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root");
}catch(Exception ex){
System.out.println("Connection failed :" +ex);
}
}
public void createProfile(Profile profile){
Statement stm = null;
try{
stm = dbConnection.createStatement();
stm.executeUpdate("INSERT INTO User (Username,Password) VALUES (\"" + profile.getUsername() + "\", \"" + profile.getPassword()+ "\"");
}catch(SQLException ex){
System.out.println(ex);
}
}
Finally in my JFrame I have two textFeilds username and password which I want to use in order to pass on the parameters for profile constructor. Once this is done I DBConnect object to start of the connection and than I'm calling the Create Profile method which is declared in the DBConnect.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Profile p = new Profile(jTextField1.getText(), jPasswordField1.getText());
DBConnect dbc = new DBConnect();
dbc.createProfile(p);
Everything compiles but when I run the program and try to create a new Profile I get this Error.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
My MySQL tables is a simple table with two columns called 'Username' and 'Password'
You need to put the right parenthesis inside the string:
stm.executeUpdate("INSERT INTO User (Username,Password) VALUES (\"" + profile.getUsername() + "\", \"" + profile.getPassword()+ "\")";
Related
I have a Springboot app that is trying to connect and read values from an app config resource.
Some keys in the Azure app config (which I am unable to change) are in this format
`
/application/config.datasource.jdbc-url
/application/config.datasource.password
/application/config.datasource.username`
I have a config Java class with prefix ("config"), but I don't know what member variables I should have in order to access "datasource.jdbc-url", "datasource.password" etc.
If the app config was just /application/config.username
then I could just use the below in my Java class
String username;
but for some of the configs that include multiple dots and some dashes (which Java identifiers can't have), how can I read the values?
Thank you!
Your use case is similar to this sample azure-spring-cloud-starter-appconfiguration-config-sample, please try to define the properties class to bind the configurations in Azure App Configuration.
Adding to #Moarchy Chan#ConfigurationProperties(prefix = "config.datasource")
In Azure portal>App configuration> Configuration explorer, I have created keys and values for Username, Password and Jdbc url.
This is my Class UserProperties,
#ConfigurationProperties(prefix = "config.datasource")
public class UserProperties {
private String username;
private String password;
private String jdbcurl;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getJdbcurl() {
return jdbcurl;
}
public void setJdbcurl(String jdbcurl) {
this.jdbcurl = jdbcurl;
}
}
Here is the UserController I have created,
public class UserController {
private final UserProperties properties;
public UserController(UserProperties properties) {
this.properties = properties;
}
#GetMapping("/Anu")
public String getUsername() {
return "username: " + properties.getUsername();
}
#GetMapping("/vyshu")
public String getPassword() {
return "password: " + properties.getPassword();
}
#GetMapping("/priya")
public String getJdbcurl() {
return "jdbcurl: " + properties.getJdbcurl();
}
}
This the bootstrap for my code, you should add your connection string in {},
spring.cloud.azure.appconfiguration.stores[0].connection-string= ${APP_CONFIGURATION_CONNECTION_STRING}
This is the output for my Username,
This is the output for my Password,
This is the output for my jdbcurl,
You have two options depending on what you are looking for. You can either use #Value("config.datasource.jdbc-url") or you can use nested properties.
public class Datasource {
private String username;
private String password;
private String jdbcurl;
...
}
#ConfigurationProperties(prefix = "config")
class MyProperties {
private Datasource datasource = new Datasource();
...
}
guys, i stuck into the middle on process writing my own first web-app. I have a couple issues with DAO layer.
Look at my first entity:
public class Fabric {
private Integer id;
private String name;
private String country;
}
There is Object, which "id" property is the foreign key for another entity:
public class Guitar {
private Integer id;
private Fabric fabric;
private String name;
private Short strings;
private Color color;
private Integer count;
}
So when i try to write DAO layer for "Guitar" entity like this:
Guitar guitar = null;
try (Connection connection = ConnectionManager.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(GET_BY_ID)) {
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
guitar = Guitar.builder()
.id(resultSet.getInt(id))
***.fabric()*** <---- idk how to get fabric id
.name(resultSet.getString("name"))
.strings(resultSet.getShort("strings"))
.color(???some jave code???) <--- this is ENUM :(
.count(resultSet.getInt("count"))
.build();
}
} catch (SQLException e) {
throw new DaoException(e);
}
return Optional.ofNullable(guitar);
} ``
SQL request: ```private static final String GET_BY_ID = "SELECT id, fabric_id, name, strings, color, count FROM shop_storage.guitar WHERE count NOTNULL";
p.s. also idk how to get enum in this object:(
If can help me - i'll appreciate it.
have a good time anyone:)
I am trying to execute this query:
#Override
public UserInfo get(Long id) {
String sql = "SELECT * FROM users WHERE id = ? ";
List<UserInfo> list = jdbcTemplate.query(sql,new UserInfoMapper(),id);
return list.get(0);
}
but jdbc return empty list and I get exception at return line.
But if try to execute directly though the console it returns:
Query, Answer
Query was executed with id 1 and retured correct anwser;
But in method its returned this
I couldn't find any same questions so that may be point at my inattention to something. But I can't see any problem that may cause this. Thanks in advance;
Updated 1
Changing code to
#Override
public UserInfo get(Long id) {
String sql = "SELECT * FROM users WHERE id = ? ";
List<UserInfo> list = jdbcTemplate.query(sql, new Object[] {id},new UserInfoMapper());
return list.get(0);
}
resulted in same: result
Updated 2
#Override
public UserInfo mapRow(ResultSet resultSet, int i) throws SQLException {
UserInfo info = new UserInfo();
info.setId(resultSet.getLong("id"));
info.setFirstname(resultSet.getString("firstname"));
info.setMiddlename(resultSet.getString("middlename"));
info.setLastname(resultSet.getString("lastname"));
info.setUsername(resultSet.getString("username"));
info.setPassword(resultSet.getString("password"));
info.setEmail(resultSet.getString("email"));
info.setMobilephone(resultSet.getString("mobilephone"));
info.setPosition(resultSet.getString("position"));
return info;
}
public class UserInfo {
private Long id;
private String firstname;
private String middlename;
private String lastname;
private String username;
private String password;
private String email;
private String mobilephone;
private String position;
public UserInfo() {
}
}
Getter and setters for each field is there but I think there is no need to show them up.
Check user credentials that you are using to connect database from your application and the user credentials in console. And also check owner schema , table owner schema in your application.
I have an application that stores users data in a text file and I need to store only unique entries (e.g. a phone book), where out of the following fields: name, mobile number, and address, mobile number would be the unique key.
I'm using the following code to write my file:
try {
line = mUserName.getText().toString() + ","
phone.getText().toString() + ","
address.getText().toString();
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
String FILENAME = path + "/UsersData.txt"; // External is the text file name
FileWriter fWriter;
BufferedWriter writer;
fWriter = new FileWriter(FILENAME, true);
writer = new BufferedWriter(fWriter);
writer.append(line);
writer.newLine();
writer.close();
} catch (Exception e) {
result.append("\n" + e.getMessage());
}
What I'd like is for the application to check whether the phone number already exists in the file before it writes the new data, and if it does we tell the user that it's already in the file.
Is it possible to do this without harming application performance?
There's another option that we could store the data in a database, then convert it to a text file when they ask for it, would that be better?
If you write 2 or more thing with single line without seperate them with a character(i.e: #,% etc) will not be logical. If username ends with a number, you will not determine that this number is character of username or phone number.
So "line = mUserName.getText().toString() + phone.getText().toString() + address.getText().toString();" is wrong.
You should create a object class which has fields as userName, phoneNumber and address as:
public class Contact {
private String userName;
private String phoneNumber; //should be string it may start with +1 123...
private String address;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Then set your contact informations as a list, save and retrieve your contact list via using GSon and shared preferences via this answer: store and retrieve a class object in shared preference
You can search user contact information via retrieving your list from shared preferences.
I have these codes
DBCollection.java
public LogInHandler userGreetName()
{
LogInHandler login = new LogInHandler();
String query = null;
try
{
query = "SELECT First_Name FROM user_information WHERE Username = '"+login.getUsername()+"'";
rs = stmt.executeQuery(query);
rs.next();
login.setGreetName(rs.getString("First_Name"));
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e.toString());
}
return login;
}
On my mainWindow.java I have formWindowOpened event and contains the codes
DBCollection dbc = new DBCollection();
greetNameL.setText(dbc.userGreetName().getGreetName());
LogInHandler.java
public class LogInHandler extends ValidateLogin{
DBCollection dbc = new DBCollection();
private String username;
private String greetName;
public void setGreetName(String temp)
{
greetName = temp;
}
public String getGreetName()
{
return greetName;
}
public void setUsername(String temp)
{
username = temp;
}
public String getUsername()
{
return username;
}
I have login.setUsername(usernameTF.getText()); in my loginWindowGUI
here's my problem.. I cant retrieve the First_Name column in my database.. it displays null. and is my WHERE condition in query is correct? help please..
Firstly, the way you've set your code exposes you to SQL injection.
query = "SELECT First_Name FROM user_information WHERE Username = '"+login.getUsername()+"'";
rs = stmt.executeQuery(query);
rs.next();
login.setGreetName(rs.getString("First_Name"));
Something like the below should do the same job as your code, but protect you from SQL injection.
query = "SELECT First_Name FROM user_information WHERE Username = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(query);
preparedStatement.setString(1, login.getUsername());
ResultSet rs = preparedStatement.executeQuery(query);
rs.next();
login.setGreetName(rs.getString("First_Name"));
I don't think that is what's causing your code not to work however. You need to give us more information.
Have you tried directly querying the DB with the following string?
SELECT First_Name FROM user_information WHERE Username = 'A user name that is definitely in the DB';
That should verify if your query is correct or not. If it works, then I would go into debug mode in Netbeans. Put a breakpoint before the following line
rs = stmt.executeQuery(query);
Check to see if login.username variable is populated. If that field is null, then your problem is there.