如何连接到Java中的数据库连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21361781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to connect to database connection in Java
提问by Jeiman
I would like to know how to connect to database in which is hosted in Xampp MySQL.
我想知道如何连接到 Xampp MySQL 中托管的数据库。
This is what I have so far in my java code to connect but I'm unsure what I'm doing.
到目前为止,这是我在 Java 代码中要连接的内容,但我不确定自己在做什么。
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection( host, username, password );
String host = "jdbc:derby://localhost:1527/Employees";
String uName = "root";
String uPass= "password";
}
catch ( SQLException err ) {
System.out.println( err.getMessage( ) );
}
}
- What would the host URL be?
- Do i need a JDBC Jar file to connect to the DB?
- 主机 URL 是什么?
- 我是否需要 JDBC Jar 文件才能连接到数据库?
I have setup a database and table via phpMyAdmin already. Just don't know how to proceed.
我已经通过 phpMyAdmin 设置了一个数据库和表。只是不知道如何继续。
I am using Netbeansto write my Java code to connect to a local database which was created via Xampp PHPMyAdmin.
我正在使用Netbeans编写我的 Java 代码以连接到通过Xampp PHPMyAdmin创建的本地数据库。
In the end, I want to create a database connection in Java and call out tables within the IDE. Would appreciate some help.
最后,我想在 Java 中创建一个数据库连接并在 IDE 中调用表。希望得到一些帮助。
采纳答案by Suganthan Madhavan Pillai
This is the project structure
这是项目结构
Try with this
试试这个
Update
更新
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/testspring","root", "password");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
It is working for me
它对我有用
I downloaded jar from Java2s.com
我从Java2s.com下载了 jar
回答by Happy
Maybe you should define your strings before use them.
也许你应该在使用它们之前定义你的字符串。
The host URL seems good.
主机 URL 看起来不错。
You have to install the driver in your server, or to put it in the /lib
folder of your project. You fill find it in %DERBY_HOME%/lib
folder, named derby.jar
, assuming %DERBY_HOME%
is the directory installation of Derby.
您必须在您的服务器中安装驱动程序,或者将其放在/lib
您的项目文件夹中。你填写在%DERBY_HOME%/lib
文件夹中找到它,命名为derby.jar
,假设%DERBY_HOME%
是Derby的安装目录。
回答by Ashot Karakhanyan
This is a code (Java 7 style, try-with-resources, more laconic style) to connect and retrieve data from your DB.
这是一个代码(Java 7 风格、try-with-resources、更简洁的风格),用于连接和检索数据库中的数据。
public static final String SELECT_QUERY = "SELECT * FROM your_table_name";
public static void main(String[] args) {
String host = "jdbc:derby://localhost:1527/Employees";
String uName = "root";
String uPass = "password";
try (Connection conn = DriverManager.getConnection(host, uName, uPass);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SELECT_QUERY)) {
while (rs.next()) {
//read your lines one ofter one
int id = rs.getInt("id");
String somePropertyValue = rs.getInt("some_column_name");
// etc.
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Also, add JDBC driver (*.jar file) in your classpath if you are running from command line, or add this jar to your project, if you are working in IDE (Eclipse, IDEA etc. It is a little bit different for each one).
此外,如果您从命令行运行,请在您的类路径中添加 JDBC 驱动程序(*.jar 文件),或者如果您在 IDE(Eclipse、IDEA 等)中工作,则将此 jar 添加到您的项目中。每个都有一点不同一)。
BTW, How your code compiled if variable declaration is after they using? That code can not be compiled even.
顺便说一句,如果变量声明是在使用之后,您的代码如何编译?那个代码甚至不能编译。
回答by Deepak Kumar
package com.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DatabaseUtil1 {
public static final String DRIVER="oracle.jdbc.driver.OracleDriver";
public static final String URL="jdbc:oracle:thin:@DIPAK-PC:1521:xe";
public static final String USERNAME="system";
public static final String PASSWORD="password";
public static Connection getConnection() throws ClassNotFoundException, SQLException
{
Connection con= null;
Class.forName(DRIVER);
con=DriverManager.getConnection(URL,USERNAME,PASSWORD);
System.out.println(con);
return con;
}
public static void closePreparedStatement(PreparedStatement pst) throws SQLException
{
if(pst!=null)
{
pst.close();
}
}
public static void closeConnection(Connection con) throws SQLException
{
if(con!=null)
{
con.close();
}
}
}
回答by Mike
Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
导入包:要求包含包含数据库编程所需的 JDBC 类的包。大多数情况下,使用 import java.sql.* 就足够了。
Register the JDBC driver: Requires that you initialize a driver so you can open a communication channel with the database.
注册 JDBC 驱动程序:需要您初始化驱动程序,以便您可以打开与数据库的通信通道。
Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
打开连接:需要使用DriverManager.getConnection()方法创建一个Connection对象,该对象代表与数据库的物理连接。
回答by Faisal shahzad
Database Connectivity:
数据库连接:
These are following step are required to connect java application with database.
这些是将 java 应用程序与数据库连接所需的以下步骤。
? Import the sql package
? 导入sql包
Import.java.sql.*;
? Load driver
? 加载驱动程序
Every database has diffirent driver,we are using sql database so driver for sql database is
Class.forName(“com.mysql.jdbc.Driver”);
Class.forName(“com.mysql.jdbc.Driver”);
? Make Url
? 制作网址
String url=”jdbc:mysql://localhost/DataBaseName”;
? Make Connection
? 建立连接
Connection con=DriverManager(url,”root”,””);
? Create Statement object
? 创建语句对象
Statement st=con.CreateStatement();
After creating statement object,we can perform sql queries on database,
? Make query
? 进行查询
String sql=”SELECT * FROM table_Name ”;
? Make ResultSet Object and Excute query
? 制作 ResultSet 对象并执行查询
ResultSet rs=st.excuteUpdate(sql);
? Important step to close the connection
? 关闭连接的重要步骤
con.close();
Noteif we do not have sql connecter in jdk first download connecter from this url https://dev.mysql.com/downloads/connector/j/5.1.htmland copy and paste into,
请注意,如果我们在 jdk 中没有 sql 连接器,请首先从此 url https://dev.mysql.com/downloads/connector/j/5.1.html下载连接器 并复制并粘贴到,
Java/jre/lib/ext
Java/jre/lib/ext