1. java連接資料庫的代碼
package mysql;
import java.sql.*;
/**
* @author xys
*/
public class ConnectMysql {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306/databaseName";
String user = "mysqluser";
String password = "password";
String driverClass = "com.mysql.cj.jdbc.Driver";
Connection connection = null;
Class.forName(driverClass);
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null) {
System.out.println("資料庫連接成功");
} else {
System.out.println("資料庫連接失敗");
connection.close();
}
return connection;
}
public void getResult() throws ClassNotFoundException, SQLException {
// 實例化 Statement 對象
Statement statement = getConnection().createStatement();
// 要執行的 Mysql 資料庫操作語句(增、刪、改、查)
String sql = "";
// 展開結果集資料庫
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
// 通過欄位檢索
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// 輸出數據
System.out.println("ID : " +id);
System.out.println("name :" + name);
}
// 完成後需要依次關閉
resultSet.close();
statement.close();
getConnection().close();
}
}
2. java連接資料庫mysql代碼及簡單訪問資料庫
import java.sql.*;
public class DataBasePractice {
public static void main(String[] args) {
//聲明Connection對象
Connection con;
//驅動程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要訪問的資料庫名mydata
String url = "jdbc:mysql://localhost:3306/mydata";
//MySQL配置時的用戶名
String user = "root";
//MySQL配置時的密碼
String password = "root";
//遍歷查詢結果集
try {
//載入驅動程序
Class.forName(driver);
//1.getConnection()方法,連接MySQL資料庫!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.創建statement類對象,用來執行SQL語句!!
Statement statement = con.createStatement();
//要執行的SQL語句
String sql = "select * from student";
//3.ResultSet類,用來存放獲取的結果集!!
ResultSet rs = statement.executeQuery(sql);
System.out.println("-----------------");
System.out.println("執行結果如下所示:");
System.out.println("-----------------");
System.out.println(" 學號" + "\t" + " 姓名");
System.out.println("-----------------");
String name = null;
String id = null;
while(rs.next()){
//獲取stuname這列數據
name = rs.getString("stuname");
//獲取stuid這列數據
id = rs.getString("stuid");
//首先使用ISO-8859-1字元集將name解碼為位元組序列並將結果存儲新的位元組數組中。
//然後使用GB2312字元集解碼指定的位元組數組。
name = new String(name.getBytes("ISO-8859-1"),"gb2312");
//輸出結果
System.out.println(id + "\t" + name);
}
rs.close();
con.close();
} catch(ClassNotFoundException e) {
//資料庫驅動類異常處理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//資料庫連接失敗異常處理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("資料庫數據成功獲取!!");
}
}
}
在上面while代碼段後面添加以下代碼段:
String name = null;
String id = null;
while(rs.next()){
//獲取stuname這列數據
name = rs.getString("stuname");
//獲取stuid這列數據
id = rs.getString("stuid");
//首先使用ISO-8859-1字元集將name解碼為位元組序列並將結果存儲新的位元組數組中。
//然後使用GB2312字元集解碼指定的位元組數組。
name = new String(name.getBytes("ISO-8859-1"),"gb2312");
//輸出結果
System.out.println(id + "\t" + name);
}
PreparedStatement psql;
ResultSet res;
//預處理添加數據,其中有兩個參數--「?」
psql = con.prepareStatement("insert into student values(?,?)");
psql.setInt(1, 8); //設置參數1,創建id為5的數據
psql.setString(2, "xiaogang"); //設置參數2,name 為小明
psql.executeUpdate(); //執行更新
//預處理更新(修改)數據
psql = con.prepareStatement("update student set stuname = ? where stuid = ?");
psql.setString(1,"xiaowang"); //設置參數1,將name改為王五
psql.setInt(2,10); //設置參數2,將id為2的數據做修改
psql.executeUpdate();
//預處理刪除數據
psql = con.prepareStatement("delete from student where stuid = ?");
psql.setInt(1, 5);
psql.executeUpdate();
//查詢修改數據後student表中的數據
psql = con.prepareStatement("select*from student");
res = psql.executeQuery(); //執行預處理sql語句
System.out.println("執行增加、修改、刪除後的數據");
while(res.next()){
name = res.getString("stuname");
id = res.getString("stuid");
name = new String(name.getBytes("ISO-8859-1"),"gb2312");
System.out.println(id + "\t" + name);
}
res.close();
psql.close();
3. 求java與資料庫連接的代碼(含注釋)
代碼主要列出連接資料庫的關鍵代碼,其他訪問資料庫代碼省略
1、Oracle8/8i/9i資料庫(thin模式)
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url="jdbc:oracle:thin:@localhost:1521:orcl";
//orcl為資料庫的SID
String user="test";
String password="test";
Connection conn= DriverManager.getConnection(url,user,password);
2、DB2資料庫
Class.forName("com.ibm.db2.jdbc.app.DB2Driver ").newInstance();
String url="jdbc:db2://localhost:5000/sample";
//sample為你的資料庫名
String user="admin";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
3、Sql Server7.0/2000資料庫
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb";
//mydb為資料庫
String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
4、Sybase資料庫
Class.forName("com.sybase.jdbc.SybDriver").newInstance();
String url =" jdbc:sybase:Tds:localhost:5007/myDB";
//myDB為你的資料庫名
Properties sysProps = System.getProperties();
SysProps.put("user","userid");
SysProps.put("password","user_password");
Connection conn= DriverManager.getConnection(url, SysProps);
5、Informix資料庫
Class.forName("com.informix.jdbc.IfxDriver").newInstance();
String url =
"jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver;
user=testuser;password=testpassword";
//myDB為資料庫名
Connection conn= DriverManager.getConnection(url);
6、MySQL資料庫
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1"
//myDB為資料庫名
Connection conn= DriverManager.getConnection(url);
7、PostgreSQL資料庫
Class.forName("org.postgresql.Driver").newInstance();
String url ="jdbc:postgresql://localhost/myDB"
//myDB為資料庫名
String user="myuser";
String password="mypassword";
Connection conn= DriverManager.getConnection(url,user,password);
4. JAVA連接資料庫連接代碼怎麼寫
1 將資料庫的JDBC驅動載入到classpath中,在基於JAVAEE的WEB應用實際開發過程中,通常要把目標資料庫產品的JDBC驅動復制到WEB-INF/lib下.
2 載入JDBC驅動,並將其注冊到DriverManager中,下面是一些主流資料庫的JDBC驅動加裁注冊的代碼:
//Oracle8/8i/9iO資料庫(thin模式)
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
//Sql Server7.0/2000資料庫
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
//DB2資料庫
Class.froName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();
//Informix資料庫
Class.forName("com.informix.jdbc.IfxDriver").newInstance();
//Sybase資料庫
Class.forName("com.sybase.jdbc.SybDriver").newInstance();
//MySQL資料庫
Class.forName("com.mysql.jdbc.Driver").newInstance();
//PostgreSQL資料庫
Class.forNaem("org.postgresql.Driver").newInstance();
3 建立資料庫連接,取得Connection對象.例如:
//Oracle8/8i/9i資料庫(thin模式)
String url="jdbc:oracle:thin:@localhost:1521:orcl";
String user="scott";
String password="tiger";
Connection conn=DriverManager.getConnection(url,user,password);
-->完整的太多了!我已經把完整的代碼發到你QQ郵箱了!
5. 如何用Java程序啟動H2資料庫(完整代碼)
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.tools.Server;
public class H2Demo {
private Server server;
private String port = "9094";
private String dbDir = "./h2db/sample";
private String user = "zhoujiang";
private String password = "123456";
public void startServer() {
try {
System.out.println("正在啟動h2...");
server = Server.createTcpServer(
new String[] { "-tcpPort", port }).start();
} catch (SQLException e) {
System.out.println("啟動h2出錯:" + e.toString());
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
}
public void stopServer() {
if (server != null) {
System.out.println("正在關閉h2...");
server.stop();
System.out.println("關閉成功.");
}
}
public void useH2() {
try {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:" + dbDir,
user, password);
Statement stat = conn.createStatement();
// insert data
stat.execute("CREATE TABLE TEST(NAME VARCHAR)");
stat.execute("INSERT INTO TEST VALUES('Hello World')");
// use data
ResultSet result = stat.executeQuery("select name from test ");
int i = 1;
while (result.next()) {
System.out.println(i++ + ":" + result.getString("name"));
}
result.close();
stat.close();
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
H2Demo h2 = new H2Demo();
h2.startServer();
h2.useH2();
h2.stopServer();
System.out.println("==END==");
}
}
6. 求:用Java連接資料庫和簡單的資料庫操作代碼
以上的代碼都不如哥的 且看哥是怎麼寫條理清晰的代碼的!!!
package dbconnection //java 中不存在沒有包的類(講解詳細因為項目需要)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;//引入sql資料庫包
public class DBConnection{
private Connection conn=null;
private Statement stmt=null;
private Result rs=null;
private String jdbc="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private String driverManager="jdbc:sqlserver://localhost:1433;databasename=HcitPos";
private String user="admin";
private int password="admin";
public DBConnection{
try{
Class.forName("jdbc");
conn.getConnection("driverManager");
}
catch(Exception e){}
}
public selectMethod(String sql){
stmt=conn.createStatement();
rs=stmt.extcuteQuery("sql");
while(rs.next()){
String title=rs.getString("title");//利用javaBean獲得資料庫中的屬性
String name=rs.getString("name");
.......
System.out.println("title");
System.out.println("name");
......
//當然資料庫的操作有很多 這里簡單介紹下功能的實現
}
}
public void closeDB(){
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(conn != null) conn.close();
}
}
7. java 操作資料庫代碼怎麼寫好
public static void main(String[] args)
{
try
{
String url="jdbc:mysql://localhost/mydb";
String user="root";
String pwd="123456";
//載入驅動,這一句也可寫為:Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").newInstance();
//建立到MySQL的連接
Connection conn = DriverManager.getConnection(url,user, pwd);
//執行SQL語句
Statement stmt = conn.createStatement();//創建語句對象,用以執行sql語言
ResultSet rs = stmt.executeQuery("select * from student");
//處理結果集
while (rs.next())
{
String name = rs.getString("name");
System.out.println(name);
}
rs.close();//關閉資料庫
conn.close();
}
catch (Exception ex)
{
System.out.println("Error : " + ex.toString());
}
}
另外記得導入相應的jar包。。。。。。。
8. java連接資料庫的方法,最好有詳細的代碼
import java.sql.*;
/*-
* Copyright(C) http://www.cn-java.com by jackliu
* 這是一個免費的代碼,如果進行修改,請保留以上信息.
* 這是一個用標准JDBC連接Oracle資料庫的包
* 編制人: Jackliu
* 開始日期: 2001.04.06
* 結束日期: 2001.04.06
* 版本: 1.0*/
public class Ora8iConnect
{
public Ora8iConnect(String db,String id,String pwd)
{ dbNAME=db;
userID=id;
userPWD=pwd;
beginConnect(); //連接資料庫
}
/*-
*返回一個Connection對象
*/
public Connection getConnection(){return conn;}
/*-
*連接資料庫,成功後返回1否則返回0
*/
public int beginConnect()
{ try
{ //載入一個Oracle驅動
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//使用OCI8連接到資料庫
conn=DriverManager.getConnection("jdbc:oracle:oci8:@"+dbNAME,userID,userPWD);
return 1;
}
catch(SQLException e) //捕捉SQL違例
{ System.out.println("Ora8iConnect在連接oracle8資料庫時捕獲");
while (e!=null)
{ System.out.println("SQLState:"+e.getSQLState());
System.out.println("Message :"+e.getMessage());
System.out.println("Vendor :"+e.getErrorCode());
e=e.getNextException();
System.out.println(" ");
}
conn=null;
return 0;
}
}
private Connection conn; //連接對象
private String dbNAME; //實例
private String userID; //用戶名
private String userPWD; //口令
}
9. java連接資料庫具體操作以及代碼!最好有個例子 越詳細越好
你要連接的是什麼資料庫
連接什麼資料庫,你就要去下載相應的驅動
package com..conn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.entity.PubTermBean;
/**
* ms sql2005連接
* @author Administrator
*
*/
public class ConnByMsSql2005 {
public static Connection getConn(){
Connection conn=null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); //載入驅動類
conn=DriverManager.getConnection("jdbc:sqlserver:127.0.0.1:1433;databasename=資料庫名","登錄資料庫名","密碼");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
//查詢資料庫表的方法
public List<Us> select() {
Connection con = null;
PreparedStatement pst = null;
ResultSet rt = null;
con = ConnByMsSql2005 .getConn();//獲得上面的連接資料庫的對象
List<Us> list = new ArrayList<Us>();
try {
String sql="select * from users";//查詢語句
pst = con.prepareStatement();
rt = pst.executeQuery();//執行查詢
while (rt.next()) { //循環查詢的結果集
//將數據封裝到javabean里
Us u = new Us();
u.setId(rt.getInt(1));
u.setName(rt.getString(2));
u.setPwd(rt.getString(3));
//將每一個javabean對象放到list集合
list.add(u);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//關閉資料庫操作對象
try {
if (rt != null) {
rt.close();
}
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return list; //返回得到的資料庫數據
}