This question already has answers here:
findbugs and database password security issue
(5 answers)
Closed 7 years ago.
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
PreparedStatement st = con.prepareStatement(
"INSERT INTO menu(menu.menuID,menu.name,menu.info,menu.price) values(?,?,?,?)");
st.setString(1, value1);
st.setString(2, value2);
st.setString(3, value3);
st.setString(4, value4);
st.executeUpdate();
JOptionPane.showMessageDialog(p1, "Data is successfully inserted into database.");
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(p1,
"Error in submitting data!");
}
I ran FindBugs and this is the bug that is coming on line 3:
Hardcoded constant database password in ie.lyit.flight.Changeadd$3.actionPerformed(ActionEvent)
This code creates a database connect using a hardcoded, constant password. Anyone with access to either the source code or the compiled code can easily learn the password.
Rank: Scary (7), confidence: Normal
Pattern: DMI_CONSTANT_DB_PASSWORD
Type: Dm, Category: SECURITY (Security)
I was wondering if anyone knows how to get rid of this bug and how I would go about doing it?
Code analysis tools check for any loop-hopes in code along-with looking for best-practices (or violations of them).
While developing, you can ignore such warning, but yes, once you done with your business logic, its always good to apply best practices - in this case read the password from a configuration or properties file.
If you are using jtd for connecting database,there is no need to provide username and password for connection.Try below code-
Connection conn = null;
String url = "jdbc:jtds:sqlserver://" +serverName+ "/" +"master";
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver);
conn = DriverManager.getConnection(url);
master is database name in my case.Just replace it with yours.
This simply tells you that passwords should not be stored directly in the source code of your application, because it is often shared and not encrypted.
Use some external source instead, and even better do not store any passwords, store password hashes only.
You may also look at:
https://stackoverflow.com/questions/tagged/pbkdf2
How can I hash a password in Java?
https://stackoverflow.com/questions/tagged/ldap
http://docs.oracle.com/javase/7/docs/api/java/security/KeyStore.html
Related
I want to save data in sql server database without username or password. the code example is given bellow. Can anyone explain the cause of not save the data into database?
Thank in advance. Please help me
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;databaseName=azan";
Connection con = null;
con = DriverManager.getConnection(url);
Statement st = con.createStatement();
String sql = "INSERT INTO huzaifa (username,password) VALUES ('"+username+"','"+password+"')";
st.executeUpdate(sql);
con.close();
}catch (Exception ex)
{
System.out.print(ex);
}//
%>
The only way you can do this is using JNDI Bound Datasource in the server. In general the way it works as follows:
Configure a datasource in the server. The username and password are part of the configuration.
The datasources is bound to to JNDI tree.
The datasource can be looked up into JNDI tree and from there a connection can be obtained.
Once you have the connection, you can fire queries.
Here is an example of how to do this in Tomcat.
I suggest you to move the database operation code in a Servlet rather than doing in JSP.
If you really you want to do in JSP as well then try to avoid Scriplet.
Use JSP Standard Tag Library and JSP Expression Language instead of using Scriplet that is more easy to manage and less error prone. Use SQL Tag Library that provides JSTL SQL tags for accessing databases in JSP.
sample code:
<sql:setDataSource var="dataSource"
driver="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost:1433;databaseName=azan" user=""
password="" />
<sql:update dataSource="${dataSource}"
sql="INSERT INTO huzaifa (username,password) VALUES ( values(?,?)">
<sql:param value="${param.username}" />
<sql:param value="${param.password}" />
</sql:update>
From a SQL Server perspective, if you don't wish to state the username and password in your application connection, you would need to use integrated security which passes the logged in user or user context that is configured in your web server.
I am not a java developer but have located the following specific to what you are trying to do and is hopefully helpful.
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/3d8da2ca-4efb-41d6-bb08-b7193cf49753/jdbc-integrated-security-problem?forum=sqldataaccess
First let me understand your question. You are getting 2 values from the parameter and save it in database. Now you are trying to save the values without the column names?am i right?.
If this is the case, then you just use the INSERT command without column names.
e.g INSERT INTO table_name
VALUES (value1,value2,value3,...);
Or else, If you want to save a value in Database without giving the Authentication Username and Password, Its not possible, I hope..
Is there a PLATFORM INDEPENDENT connection string for EXCEL file in java. jdbc:odbc is platform dependent. Is there anything else ??
In this post you could see an example of using a connection string without the ODBC. I suppose this is what you are looking for...
Class.forName("com.hxtt.sql.excel.ExcelDriver").newInstance();
String url = "jdbc:Excel:///E:/JavaWithExcel/Feedback.xlsx";
String sql = "select * from [Sheet1]";
Connection con = DriverManager.getConnection(url, "", "");
Statement stmt = con.createStatement();
System.out.println(con);
System.out.println(stmt);
stmt.close();
con.close();
Anyway, you have to understand that the connection string is always specific to the underlying environment. It could depend on the operating system, on the file system or something else... I would just use different configuration files for each environment.
Hope I helped!
I've been able to use Java and HTMLUnit to scrape a web page, however I'm unsure how I can get this to write the resulting data to a MySQL database on a remote hosted server. I also need this to happen at regular intervals (perhaps once a day) if possible, without having to manually run the program.
Is this possible and can I have any guidance, thorough or not, on how to do this?
Thanks!
Get your page's HTML into some String variable
String scrapedHtml = "";
Create a table in mysql with a text field
create table html_store (
id int primary key autoincrement,
content text not null
);
Use JDBC code to connect to the database and inset the data. Set the connectionURL and other parameters correctly
Connection conn = DriverManager.getConnection(connectionURL, user, password);
PreparedStatement pstmt =
conn.prepareStatement("insert into html_store (content) values (?)");
pstmt.setString(1, scrapedHtml);
pstmt.executeUpdate();
pstmt.close();
conn.close();
I have a problem with a really slow connection between my Java code and a MySQL Database. I don't know where the bottle neck is.
My program is more or less a chatbot. The user types something in, my program splits the sentence into words and sends it word per word to the database. If it finds something there, the user gets an output.
The database is on an external Server, but I also tried to connect to a pc next to me. Both is slow.
I tried the connection once at another place then where I normally work and there it was fast, most of the time.
My SQL Code:
SELECT info.INFORMATION FROM INFORMATION info, INFO_SCHLUESSEL sch
WHERE LCASE(sch.SCHLUESSELWORT) LIKE '" + input + "%' AND info.ID_INFO = sch.ID_INFO
Order BY info.PRIORITAET DESC LIMIT 1;
(just remembered, if it helps to understand the sql code:
schluessel = key
Schluesselwort = key word
prioritaet = priority)
My Java Database Code is more or less standard stuff:
String driver = "com.mysql.jdbc.Driver";
String dbase = "jdbc:mysql://bla";
String dbuser = "bla";
String dbpw = "bla";
Class.forName(driver);
Connection con = DriverManager.getConnection(dbase, dbuser, dbpw);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
ergebnis = rs.getString("info.INFORMATION");
}
rs.close();
stmt.close();
con.close();
edit:
I have tried this DBCP for a while now, and I can't seem to get it to work. It seems to be as slow as the old connection. This is the example provided by the website that I use:
GenericObjectPool connectionPool = new GenericObjectPool(null);
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:mysql://bla", "bla", "bla");
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
PoolingDriver driver = new PoolingDriver();
driver.registerPool("example",connectionPool);
Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:example");
I suspect that it's the connection setup that is causing the problem. It would be worth timing how long this takes:
Connection con = DriverManager.getConnection(dbase, dbuser, dbpw);
and if so, check out Apache Commons DBCP, which allows you to pool database connections.
Well I think this warrants a discussion on the design.There are a few things which you can do in order to improve the performance. Since you are not persisting anything here, its better to preload all the data in memory in some custom java object, a map, list or whatever and then do an in-memory lookup for the word and get the results. Another approach could be to use a batch statement so that you dont go ahead and create and release connections for each word. Oh and if using batch statements make sure you set the batch size to an appropriate number, preferably a prime number
I am working a Airsoft application.
I'm trying to add records to a MS Access Database via SQL in Java. I have established a link to the database, with the following:
try
{
//String Driver = "sun.java.odbc.JdbcOdbcDriver";
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://" + URL,"","");
Statement stmt = conn.createStatement();
System.out.println("Connection Established!");
ResultSet rs = stmt.executeQuery("SELECT * FROM AirsoftGunRentals");
tblRent.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Error");
}
I am using Ucanaccess to access my MS database. It is reading the database and is displaying to a JTable. However, I need to create three JButtons to add, delete and update the table. I have tried to code the add button, and I have tried to add a record, but it crashes and gives me errors.
try
{
//String Driver = "sun.java.odbc.JdbcOdbcDriver";
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://" + URL,"","");
Statement stmt = conn.createStatement();
System.out.println("Connection Established!");
String Query= "INSERT INTO AirsoftGunRentals(NameOfGun, Brand, TypeOfGuns, NumberOfMagazines,Extras,NumberAvailable,UnitRent)"+
"VALUES('"+pName+"','"+pBrand+"','"+pTypeOfGun+"','"+pNumMags+"','"+pExtras+"','"+pNumberAvail+"','"+pRent+"');";
ResultSet rs = stmt.executeQuery(Query);
JOptionPane.showMessageDialog(null, "Success!");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Error");
}
I have attempted all three, hoping for a result. But am still getting big errors. The only difference between the buttons is that one adds, one deletes and one updates the table. Other then that, the code is the same, minus variables.
As Brahim mentionned it, you should use stmt.executeUpdate(Query) whenever you update / insert or delete data. Also with this particular query, given your String concatenation (see end of line), there is no space between the ")" and the "VALUES" which probably causes a malformed query.
However, I can see from your code that you are not very experienced with such use-cases, and I'd like to add some pointers before all hell breaks loose in your project :
Use PreparedStatement instead of Statement and replace variables by placeholders to prevent SQL Injection.
The code that you are using here is extremely prone to SQL injection - if any user has any control over any of the variables, this could lead to a full database dump (theft), destruction of data (vandalism), or even in machine takeover if other conditions are met.
A good advice is to never use the Statement class, better be safe than sorry :)
Respect Java Conventions (or be coherent).
In your example you define the String Query, while all the other variables start with lower-case (as in Java Conventions), instead of String query. Overtime, such little mistakes (that won't break a build) will lead to bugs due to mistaking variables with classnames etc :)
Good luck on your road to mastering this wonderful language ! :)
First add a space before the quotation marks like this :
String Query= "INSERT INTO AirsoftGunRentals(NameOfGun, Brand, TypeOfGuns, NumberOfMagazines,Extras,NumberAvailable,UnitRent) "+
" VALUES('"+pName+"','"+pBrand+"','"+pTypeOfGun+"','"+pNumMags+"','"+pExtras+"','"+pNumberAvail+"','"+pRent+"');";
And use stmt.executeUpdate(Query); instead of : stmt.executeQuery(Query);in your insert, update and delete queries. For select queries you can keep it.
I managed to find an answer on how to add, delete and update records to a MS Access DB. This is what I found, after I declared the connection, and the prepped statement. I will try to explain to the best I can. I had to add values individually using this:
(pstmt = Prepped Statement Variable)
pstmt.setWhatever(1,Variable);
And it works fine now. I use the same method to delete and update records.
This is the basic query format:
String SQLInsert = "INSERT INTO Tbl VALUES(NULL,?,?,?,?)";
The NULL in the statement is the autonumber in the table. and .setWhatever() clause replaces the question marks with the data types. Thus manipulating the database.
Thank you everyone for all your contributions. It helped a lot, and made this section a lot more understandable.