java里如何输写连接数据库的语句?
发布网友
发布时间:2022-04-10 02:08
我来回答
共5个回答
热心网友
时间:2022-04-10 03:38
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;
import java.sql.*;
import java.util.PropertyResourceBundle;
public class MySqlConnector {
/*
* 先在bin目录下新建一个dbCon.ini文件,连的是mysql
* 内容 如下:
* userName=你的数据库用户名
* password=你的数据库用户密码
* database=要连接的数据库名称
*/
private static final String CON_NAME = "userName";
private static final String CON_PASS = "password";
private static final String CON_DNAME = "databaseName";
private Connection connection = null;
private MySqlConnector() {
}
public static MySqlConnector getInstance() {
return new MySqlConnector();
}
private boolean dataInit() {
boolean isOK = false;
String userName = "";
String password = "";
String databaseName = "";
PropertyResourceBundle rBoundle = null;
try {
String conPath = MySqlConnector.class.getResource("/").toString() + "/dbCon.ini";
URI uri = new URI(conPath);
File file = new File(uri);
rBoundle = new PropertyResourceBundle(new FileInputStream(file));
userName = rBoundle.getString(MySqlConnector.CON_NAME);
password = rBoundle.getString(MySqlConnector.CON_PASS);
databaseName = rBoundle.getString(MySqlConnector.CON_DNAME);
String url;
url = "jdbc:mysql://localhost/" + databaseName + "?user="
+ userName + "&password=" + password;
System.out.println(url);
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url);
isOK = true;
} catch (Exception e) {
e.printStackTrace();
isOK = false;
}
return isOK;
}
public Connection getConnection() {
if (dataInit()) {
return connection;
} else {
return null;
}
}
public void close() {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
热心网友
时间:2022-04-10 04:56
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =DriverManager.getConnection("jdbc:odbc:qqdb","sa","");
Statement st=con.createStatement();
ResultSet re=st.executeQuery("select * from UserInformation where userName='"+name+"' and userPwd='"+pwd+"'");
if(re.next())
{ HttpSession session=request.getSession();
session.setAttribute("User",name);
response.sendRedirect("/MyWeb/jsp/getSession.jsp");
}
else
response.sendRedirect("Login.html");
con.close();
}catch(Exception ex){}
不懂的留言
没打补丁 1433端口就没有被启动 打了补丁就好了
热心网友
时间:2022-04-10 06:30
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver")
Connection con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=DBName","sa","sa")
热心网友
时间:2022-04-10 08:22
是想输出sql的执行语句吗?
那还得用hibernate框架才可以呢
热心网友
时间:2022-04-10 10:30
有可能服务没有开启,像我用mysql在本地服务都会有个名为mysql的服务,得开启才能为应用程序提供服务.