我正在尝试将JAVA连接到SQL SERVER,但我不知道该怎么做,上学期我们制作了一个使用MS ACCESS作为数据库的程序,我想知道我是否也可以使用它将我正在创建的程序连接到 SQL SERVER。
这是我在 Java.Main 中使用的代码:
package pkg3a3pgroupsix;
import java.sql.*;
import javax.swing.*;
public class Main {
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
Statement s;
public static Connection ConnectDatabase(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=BillingSystem.mdb");
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
public static void main(String[] args) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
// TODO code application logic here
}
}
这是我用来登录的代码:
package pkg3a3pgroupsix;
import java.awt.*;
import java.nio.channels.SeekableByteChannel;
import javax.swing.*;
import java.sql.*;
public class Login extends javax.swing.JFrame {
Connection conn;
ResultSet rs = null;
PreparedStatement pst = null;
int counter = 0;
public void registration(){
User_Registration ur = new User_Registration();
ur.setVisible(true);
ur.setExtendedState(MAXIMIZED_BOTH);
this.dispose();
}
public void exit (){
int selectedOption = JOptionPane.showConfirmDialog(null,
"Do you wanna close the window?",
"Exit",
JOptionPane.YES_NO_OPTION);
if (selectedOption == JOptionPane.YES_OPTION) { this.dispose();}
}
public Login() {
initComponents();
}
private void btnloginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sqllogin = "select * from Employee where Username='" + jTextField1.getText() + "' and Password='" + jPasswordField1.getText() + "'";
try {
pst = conn.prepareStatement(sqllogin);
rs = pst.executeQuery();
if (rs.next()) {
SelectionScreen s = new SelectionScreen();
s.setVisible(true);
this.dispose();counter = 0;}
else {JOptionPane.showMessageDialog(null, "Invalid Username or Password!");counter += 1;
if (counter == 1) {JOptionPane.showMessageDialog(null, "WARNING! 1st Attempt of Log-In!");}
else if (counter == 2) {JOptionPane.showMessageDialog(null, "WARNING! 2nd Attempt of Log-In!");}}
if (counter == 3) {JOptionPane.showMessageDialog(null, "WARNING! 3rd Attempt of Log-In!");
{JOptionPane.showMessageDialog(null, "The Program Will Shutdown.");this.dispose();}}}
catch (Exception e) {JOptionPane.showMessageDialog(null, e);}
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
conn = Main.ConnectDatabase();
}
private void btnexitActionPerformed(java.awt.event.ActionEvent evt) {
exit();
}
private void btnAdminActionPerformed(java.awt.event.ActionEvent evt) {
String sqllogin = "select * from Login where Username='" + jTextField1.getText() + "' and Password='" + jPasswordField1.getText() + "'";
try {
pst = conn.prepareStatement(sqllogin);
rs = pst.executeQuery();
if (rs.next()) {
User_Registration UR = new User_Registration();
UR.setVisible(true);
this.dispose();counter = 0;}
else {JOptionPane.showMessageDialog(null, "Invalid Username or Password!");counter += 1;
if (counter == 1) {JOptionPane.showMessageDialog(null, "WARNING! 1st Attempt of Log-In!");}
else if (counter == 2) {JOptionPane.showMessageDialog(null, "WARNING! 2nd Attempt of Log-In!");}}
if (counter == 3) {JOptionPane.showMessageDialog(null, "WARNING! 3rd Attempt of Log-In!");
{JOptionPane.showMessageDialog(null, "The Program Will Shutdown.");this.dispose();}}}
catch (Exception e) {JOptionPane.showMessageDialog(null, e);}
}
我可以使用这个吗?
最佳答案
要从 Java 应用程序连接到 MS SQL Server,您需要使用 JDBC API
。 JDBC API
提供连接到数据库、加载适当的驱动程序、发送 SQL 查询、检索结果等的类和方法。
如何连接到数据库:“Connection
”对象表示与数据库的连接。要建立连接,请使用“DriverManager.getConnection
”方法。此方法采用一个包含 URL 的字符串,该 URL 代表我们尝试连接的数据库。下面是建立连接的示例代码:
private String DATABASE_URL = "jdbc:odbc:embedded_sql_app"; // establish connection to database
Connection connection = DriverManager.getConnection( DATABASE_URL,"sa","123" );
有关数据库 URL 以及如何创建它的详细讨论可以在本文末尾提供的资源中找到。
查询数据库:JDBC API
提供了三个用于向数据库发送SQL语句的接口(interface),以及“Connection
”中相应的方法。接口(interface)创建它们的实例。
1. Statement
- 由“Connection.createStatement
”方法创建。 “Statement
”对象用于发送不带参数的 SQL 语句。
2. PreparedStatement
- 由“Connection.prepareStatement
方法”创建。 “PreparedStatement
”对象用于预编译 SQL 语句。它们可以将一个或多个参数作为输入参数(IN
参数)。
3. CallableStatement
- 由“Connection.prepareCall
”方法创建。 “CallableStatement
”对象用于从 Java 数据库应用程序执行 SQL 存储过程。
检索结果:“ResultSet
”是一个 Java 对象,其中包含执行 SQL 查询的结果。存储在“ResultSet
”对象中的数据是通过一组 get 方法检索的,这些方法允许访问当前行的各个列。 “ResultSet.next
”方法用于移动到“ResultSet
”的下一行,使其成为当前行。以下代码片段执行一个查询,该查询返回行集合,其中列“a
”为“int
”,列“b
”作为“String
”,列“c
”作为“float
”:
java.sql.Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) { // retrieve and print the values for the current row
int i = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
System.out.println("ROW = " + i + " " + s + " " + f);
}
这只是关于如何从 Java 与数据库交互的简要介绍。有关上面讨论的项目的更多详细信息以及有关传递参数、执行存储过程等的信息,请参阅以下资源:( http://www.shahriarnk.com/embedding-sql-c-sharp-java-shahriar/#Shahriar_N_Embedding_SQL_in_Java ) 在这里,您还将找到有关如何以编程方式与数据库交互的信息;即不使用 SQL。希望您觉得这很有用。
关于java - 将 JAVA 应用程序连接到 SQL SERVER,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15754912/