package com.silicon.core;
import java.sql.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class jdbcConnection implements jdbc {
public static Connection con;
public static void Createconnection() {
try {
Class.forName(jdbcConnection.urls);
con =DriverManager.getConnection(jdbcConnection.url,jdbcConnection.username,jdbcConnection.password);
System.out.println("Connection created..!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
我需要将包连接到另一个包,下面给出两个代码,jdbcConnection(连接con)来包jdbc插入。 在日食中。错误如下
jdbc selectall(); 需要将上面的程序变量“con”连接到下面的代码连接con
package com.silicon.crud;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
import com.silicon.core.jdbcConnection;
public class CRUDimpl implements Icrud {
public static void main(String[] args) {
jdbcConnection j= new jdbcConnection();
CRUDimpl u=new CRUDimpl();
u.insert();
u.update();
u.delete();
sellectall();
}
public static void sellectall() {
try {
PreparedStatement ps = con.prepareStatement("select * from employee");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
int Eid = rs.getInt(1);
String Ename = rs.getString(2);
int Eage = rs.getInt(3);
float Esalary =rs.getFloat(4);
System.out.println(Eid +" "+Ename+" "+Eage+" "+Esalary);
}
}catch(Exception e) {
e.printStackTrace();
}
}
想要这个决心。 MYSQL连接 在日食
首先应该是:
PreparedStatement ps = jdbcConnection.con.prepareStatement("select * from employee");
因为
con
是类 jdbcConnection
的静态成员。import static com.silicon.core.jdbcConnection;
.
.
.
PreparedStatement ps = con.prepareStatement("select * from employee");
但是这仍然不起作用,因为
con
是在main
类的方法jdbcConnection
中初始化的。
我建议您将类
jdbcConnection
设为 singleton – 如下面的代码所示。JdbcConnection
的 static 初始值设定项中使用虚拟值,因为我无法从您的问题中确定要使用什么值。我确信您可以提供这些值。
顺便说一句,我更改了类的名称
jdbcConnection
以遵守Java命名约定。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CRUDimpl {
public static void main(String[] args) {
sellectall();
}
public static void sellectall() {
try {
PreparedStatement ps = JdbcConnection.getConnection().prepareStatement("select * from employee");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
int Eid = rs.getInt(1);
String Ename = rs.getString(2);
int Eage = rs.getInt(3);
float Esalary =rs.getFloat(4);
System.out.println(Eid +" "+Ename+" "+Eage+" "+Esalary);
}
}catch(Exception e) {
e.printStackTrace();
}
}
}
class JdbcConnection {
private static final Connection con;
static {
try {
con = DriverManager.getConnection("url", "user", "password");
}
catch (SQLException xSql) {
throw new ExceptionInInitializerError(xSql);
}
}
public static Connection getConnection() {
return con;
}
}