Java新手需要帮助数据库连接 [英] Java newbie needs help in database connection
问题描述
我是Java的新手,甚至更新到java数据库连接。我设法创建一个数据库连接和查询表,当我把它放在Main类中。现在我把它移动到一个新类名为Connection我收到错误:
I'm new to Java and even newer to java database connections. I've managed to create a database connection and query a table when I put it in the Main class. Now that I've moved it into a new class called Connection I am getting errors:
package lokate;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class Connection {
private static Statement stmt = null;
private static ResultSet rs = null;
private static Connection con = null;
public Connection() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/Lokate?" +
"user=root&password=";
con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
retriveData("SELECT * FROM Users");
int rowsEffected = 0;
} catch (SQLException sqlEx) {
System.out.println("SQL Exception: "+ sqlEx.toString());
} catch (ClassNotFoundException classEx) {
System.out.println("Class Not Found Exception: "+ classEx.toString());
} catch (Exception Ex) {
System.out.println("Exception: "+ Ex.toString());
}
}
public static void retriveData(String SQL) throws Exception {
rs = stmt.executeQuery(SQL);
while (rs.next())
{
System.out.println(rs.getString("fname") + " : " + rs.getString("lname"));
}
}
}
m得到一个错误说找不到符号。符号:方法createStatement()和无法比较的类型为con = DriveManager .....
I'm getting an error saying cannot find symbol. Symbol:method createStatement() and incomparable types for con = DriveManager.....
任何人都可以帮助?
另外,最好的做法是将连接放在类中,这样每次我想用db做一些事情时调用一个新对象。
Also, is it best practice to put the connection in the class like this then call a new object every time I want to do something with the db?
比利
推荐答案
的许多最坏的做法。让我来计算一下方法:
I'd say your code is an example of many worst practices. Let me count the ways:
- 你的Connection类是一个糟糕的抽象,不提供java.sql.Connection。 / li>
- 如果你使用你的类,你永远不会利用连接池。
- 你连接你的驱动类,等等。你不能在不编辑和重新编译的情况下改变它。
- 在catch块中打印错误消息远远少于提供整个堆栈跟踪的信息。
- 你的代码伤害了我的眼睛。它不遵循Sun Java编码标准。
- 您的
retrieveData
方法是毫无价值的。你将如何处理所有这些印刷的声明? - 这是
rowsAffected
- 影响是动词,效果是名词。
- Your Connection class is a poor abstraction that offers nothing over and above that of java.sql.Connection.
- If you use your class, you'll never get to take advantage of connection pooling.
- You hard wire your driver class, your connection URL, etc. You can't change it without editing and recompiling. A better solution would be to externalize such things.
- Printing an error message in the catch blocks is far less information than supplying the entire stack trace.
- Your code hurts my eyes. It doesn't follow the Sun Java coding standards.
- Your
retrieveData
method is utterly worthless. What will you do with all those printed statements? Wouldn't it be better to load them into a data structure or object so the rest of your code might use that information? - It's
rowsAffected
- "affect" is the verb, "effect" is the noun. Another variable that's not doing any good.
错误的轨道。请重新思考。
You're on the wrong track. Rethink it.
我认为您会发现此代码更有帮助。
I think you'll find this code more helpful.
package persistence;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DatabaseUtils
{
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Class.forName(driver);
if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0))
{
return DriverManager.getConnection(url);
}
else
{
return DriverManager.getConnection(url, username, password);
}
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement st)
{
try
{
if (st != null)
{
st.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static List<Map<String, Object>> map(ResultSet rs) throws SQLException
{
List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
try
{
if (rs != null)
{
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
while (rs.next())
{
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= numColumns; ++i)
{
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(name, value);
}
results.add(row);
}
}
}
finally
{
close(rs);
}
return results;
}
}
这篇关于Java新手需要帮助数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!