Ⅰ java怎樣將讀取數據寫入資料庫
就要鏈接資料庫,可以通過JDBC鏈接。
首先,在連接資料庫之前必須保證SQL Server 2012是採用SQL Server身份驗證方式而不是windows身份驗證方式,開始如下配置:
一、因為SQL Server 2012裝好後,默認協議是沒有開啟的,所以要打開SQL Server配置管理器中開啟。
1、安裝好SQL Server 2012後,運行 開始 → 所有程序 → Microsoft SQL Server 2012 → 配置工具 →SQL Server配置管理器
2、在左邊欄找到 SQL Server網路配置選項,點開它的小箭頭,會看到「【你的資料庫名】的協議」 (圖中是ERIC2012的協議),選中它,看右邊欄。
(1)如果Named Pipes 未啟用,則右鍵→啟用
(2)右鍵單擊 TCP/IP,選擇 啟用
(3)雙擊TCP/IP(右鍵→屬性),在彈出的窗口中選擇 「IP地址」 選項卡,將IP1和IP10的【IP地址】設為127.0.0.1,並將所有【IPx】的【已啟用】設為是。接著,拖動下拉條到最下方,將 IPAll 中的【TCP埠】設成 【1433】,其餘不變。
3、重新啟動計算機。
4、接下來使用telnet命令測試1433埠是否打開。首先要保證telnet服務開啟。
5、完成上一步後。開始菜單 → 運行cmd → 輸入:telnet 127.0.0.1 1433,(注意telnet與127之間有空格,1與1433之間有空格)。
6、若提示「不能打開到主機的連接,在埠 1433: 連接失敗」,則說明1433埠沒有打開,需要重新進行以上配置。
Ⅱ java怎麼將收集到的數據存入資料庫
你要達到的目的其實就是在jvm啟動的時候把資料庫數據載入一份到內存,一個靜態變數和一個靜態初始化塊就可以搞定你的問題,這兩者都是在類載入的時候初始化一次,像前面回答的一樣,你可以用一個HashMap搞定。
稍微具體來說,一個靜態變數
public static final Map<key,value> cache=new HashMap<key,value>()
static {
cache=請求資料庫操作
}
key你自己加,String還是int都行,value是你資料庫的結構,可以寫個實體。獲取的時候直接cache.get(key)就可以了。
Ⅲ java怎樣將讀取數據寫入資料庫
Java可以使用JDBC對資料庫進行讀寫。JDBC訪問一般分為如下流程:
一、載入JDBC驅動程序:
在連接資料庫之前,首先要載入想要連接的資料庫的驅動到JVM(Java虛擬機), 這通過java.lang.Class類的靜態方法forName(String className)實現。
例如:
try{
//載入MySql的驅動類
Class.forName("com.mysql.jdbc.Driver") ;
}catch(ClassNotFoundException e){
System.out.println("找不到驅動程序類 ,載入驅動失敗!");
e.printStackTrace() ;
}
成功載入後,會將Driver類的實例注冊到DriverManager類中。
二、提供JDBC連接的URL 連接URL定義了連接資料庫時的協議、子協議、數據源標識。
書寫形式:協議:子協議:數據源標識 協議:在JDBC中總是以jdbc開始
子協議:是橋連接的驅動程序或是資料庫管理系統名稱。
數據源標識:標記找到資料庫來源的地址與連接埠。
例如:(MySql的連接URL)
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk
useUnicode=true:表示使用Unicode字元集。如果characterEncoding設置為
gb2312或GBK,本參數必須設置為true 。characterEncoding=gbk:字元編碼方式。
三、創建資料庫的連接
要連接資料庫,需要向java.sql.DriverManager請求並獲得Connection對象,該對象就代表一個資料庫的連接。
使用DriverManager的getConnectin(String url,String username,String password )方法傳入指定的欲連接的資料庫的路徑、資料庫的用戶名和密碼來獲得。
例如:
//連接MySql資料庫,用戶名和密碼都是root
String url = "jdbc:mysql://localhost:3306/test" ;
String username = "root" ;
String password = "root" ;
try{
Connection con =
DriverManager.getConnection(url , username , password ) ;
}catch(SQLException se){
System.out.println("資料庫連接失敗!");
se.printStackTrace() ;
}
四、創建一個Statement
要執行SQL語句,必須獲得java.sql.Statement實例,Statement實例分為以下3種類型:
1、執行靜態SQL語句。通常通過Statement實例實現。
2、執行動態SQL語句。通常通過PreparedStatement實例實現。
3、執行資料庫存儲過程。通常通過CallableStatement實例實現。
具體的實現方式:
Statement stmt = con.createStatement() ;
PreparedStatement pstmt = con.prepareStatement(sql) ;
CallableStatement cstmt = con.prepareCall("{CALL demoSp(? , ?)}") ;
五、執行SQL語句
Statement介面提供了三種執行SQL語句的方法:executeQuery 、executeUpdate和execute
1、ResultSet executeQuery(String sqlString):執行查詢資料庫的SQL語句,返回一個結果集(ResultSet)對象。
2、int executeUpdate(String sqlString):用於執行INSERT、UPDATE或DELETE語句以及SQL DDL語句,如:CREATE TABLE和DROP TABLE等
3、execute(sqlString):用於執行返回多個結果集、多個更新計數或二者組合的語句。
具體實現的代碼:
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;
int rows = stmt.executeUpdate("INSERT INTO ...") ;
boolean flag = stmt.execute(String sql) ;
六、處理結果 兩種情況:
1、執行更新返回的是本次操作影響到的記錄數。
2、執行查詢返回的結果是一個ResultSet對象。
ResultSet包含符合SQL語句中條件的所有行,並且它通過一套get方法提供了對這些行中數據的訪問。
使用結果集(ResultSet)對象的訪問方法獲取數據:
while(rs.next()){
String name = rs.getString("name") ;
String pass = rs.getString(1); // 此方法比較高效(列是從左到右編號的,並且從列1開始)
}
七、關閉JDBC對象
操作完成以後要把所有使用的JDBC對象全都關閉,以釋放JDBC資源,關閉順序和聲明順序相反:
1、關閉記錄集
2、關閉聲明
3、關閉連接對象
if(rs != null){ // 關閉記錄集
try{
rs.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(stmt != null){ // 關閉聲明
try{
stmt.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(conn != null){ // 關閉連接對象
try{
conn.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
(3)jaa如何把數據寫入資料庫擴展閱讀
樣例
package first;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheledExecutorService;
import java.util.concurrent.TimeUnit;
public class lianjie {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
public void run() {
//聲明Connection對象
Connection con;
//驅動程序名
String driver1 = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//URL指向要訪問的資料庫名
String url1 = "jdbc:sqlserver://IP地址和埠號;DateBaseName=資料庫名";
//MySQL配置時的用戶名
String user1 = "user";
//MySQL配置時的密碼
String password1 = "user";
//聲明Connection對象
Connection con1;
//驅動程序名
String driver2 = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//URL指向要訪問的資料庫名
String url2 = "jdbc:sqlserver://IP地址和埠號;DateBaseName=資料庫名";
//MySQL配置時的用戶名
String user2 = "user";
//MySQL配置時的密碼
String password2 = "user";
//遍歷查詢結果集
try {
//載入驅動程序
Class.forName(driver1);
//1.getConnection()方法,連接MySQL資料庫!!
con = DriverManager.getConnection(url1,user1,password1);
if(!con.isClosed())
System.out.println("成功連接到資料庫!");
try {
//載入驅動程序
Class.forName(driver2);
//1.getConnection()方法,連接MySQL資料庫!!
con1 = DriverManager.getConnection(url2,user2,password2);
if(!con1.isClosed())
System.out.println("成功連接到資料庫!");
//2.創建statement類對象,用來執行SQL語句!!
Statement statement = con.createStatement();
//要執行的SQL語句
String sql = "use 資料庫名 select * from 表名";
//3.ResultSet類,用來存放獲取的結果集!!
ResultSet rs = statement.executeQuery(sql);
//要執行的SQL語句
String sql1 = "use tiantiana insert into Table_1(tiantian,qiqi,yuyu)VALUES(?,?,?)";
//3.ResultSet類,用來存放獲取的結果集!!
PreparedStatement pst = con1.prepareStatement(sql1);
System.out.println ("tiantian"+"/t"+"qiqi"+"/t"+"yuyu");
while(rs.next()){
System.out.print(rs.getString(1));
System.out.print(rs.getString(2));
System.out.print(rs.getString(3));
pst.setString(1,rs.getString(1));
pst.setString(2,rs.getString(2));
pst.setString(3,rs.getString(3));
pst.executeUpdate();
}
pst.close();
rs.close();
//2.創建statement類對象,用來執行SQL語句!!
Statement statement1 = con.createStatement();
//要執行的SQL語句
String sql2 = "use 資料庫名 select * from 表名";
//3.ResultSet類,用來存放獲取的結果集!!
ResultSet rs1 = statement1.executeQuery(sql2);
//要執行的SQL語句
String sql3 = "use tiantiana insert into Table_2(tiantian1,qiqi1,yuyu1)VALUES(?,?,?)";
//3.ResultSet類,用來存放獲取的結果集!!
PreparedStatement pst1 = con1.prepareStatement(sql3);
System.out.println ("tiantian1"+"/t"+"qiqi1"+"/t"+"yuyu1");
while(rs1.next()){
System.out.print(rs1.getString(1));
System.out.print(rs1.getString(2));
System.out.print(rs1.getString(3));
pst1.setString(1,rs1.getString(1));
pst1.setString(2,rs1.getString(2));
pst1.setString(3,rs1.getString(3));
pst1.executeUpdate();
}
//關閉鏈接
rs1.close();
pst.close();
con1.close();
con.close();
} catch(ClassNotFoundException e) {
//資料庫驅動類異常處理
System.out.println("對不起,找不到驅動程序!");
e.printStackTrace();
} catch(SQLException e) {
//資料庫連接失敗異常處理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("資料庫數據成功獲取!!");
}
} catch(ClassNotFoundException e) {
//資料庫驅動類異常處理
System.out.println("對不起,找不到驅動程序!");
e.printStackTrace();
} catch(SQLException e) {
//資料庫連接失敗異常處理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("資料庫數據成功獲取!!");
}
}
};
ScheledExecutorService service = Executors
.();
// 第二個參數為首次執行的延時時間,第三個參數為定時執行的間隔時間
service.scheleAtFixedRate(runnable, 10, 60*2, TimeUnit.SECONDS);
}
}
Ⅳ java 寫入資料庫
1:首先寫一個方法是接收數據後保存至資料庫的方法,但是添加進去的數據需要進行標識(主要考慮到如果數據量較大,在保存的過程中可能有新的數據進來會產生多條數據,所以需要數據標識);
2:當點擊按鈕時彈出標識的數據,記錄ID號;
3:將修改後的數據根據ID號保存更新至資料庫中並取消該數據的標識;
Ⅳ 怎樣用Java實現從文本文檔中讀取數據並存入資料庫
不知道你要什麼樣的文本,文本中的內容是否是有格式的:
這里提供下思路,供參考:
1.文本文件,基本上式字元格式的了,可以用Readerio流
2.如果是格式化的文本,可以按數據的長度讀取,readIntreadByte...
3.保存到資料庫當然用JDBC了,如果你讀取出來封裝成POJO了,也可以選擇OM框架
importjava.io.BufferedReader;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
/**
*文件讀取和寫入資料庫
*@author樊雲升
*
*/
publicclassFilesReader{
publicFilesReader(){
}
/**
*讀取文件內容
*@paramFILE
*@return
*/
publicStringre_content(StringFILE){
Stringcontent="";
try{
BufferedReaderbufRead=newBufferedReader(newInputStreamReader(newFileInputStream(FILE)));
Stringstr;
while((str=bufRead.readLine())!=null){
content+=str+" ";
}
}catch(IOExceptionioe){
ioe.printStackTrace();
}
returncontent;
}
/**
*將特定字元寫入資料庫中(原來我寫的是重寫文件,你這里這里將content寫入資料庫就OK)
*@parampath
*@return
*/
publicbooleanwriteFile(Stringcontent){
try{
//資料庫寫入代碼
}catch(Exceptione){
out.close();
returnfalse;
}
returntrue;
}
publicstaticvoidmain(String[]args){
Stringcontent=newFilesReader().re_content("D:\AJAX.htm");
newFilesReader().writeFile(content);
}
}
Ⅵ 用java怎樣把數據存到資料庫中
只能寫個大概的,要寫數據到資料庫中,先得在資料庫中建庫,庫里建表,表裡建欄位,然後java里建立資料庫連接,用SQL語言寫數據到表中的欄位x0dx0aClass.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); x0dx0a//String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=資料庫名"; //7.0、2000x0dx0aString url="jdbc:sqlserver://localhost:1433;DatabaseName=資料庫名"; //2005x0dx0aConnection conn=null;x0dx0aconn= DriverManager.getConnection(url,用戶名,密碼); x0dx0aPreparedStatement pst=null;x0dx0apst=conn.prepareStatement("Insert Into grade(表名) Values (?)");x0dx0apst.setInt(1,你要寫的整弄數據);x0dx0a//pst.setString(2,你要寫的字元串數據);x0dx0apst.addBatch();x0dx0apst.executeBatch();
Ⅶ java如何將數據添加到資料庫中
jdbc從資料庫里取數據的resultset,然後拼裝成list或是string
通過request.setattribute(list,list)方法傳遞到前台,使用select%listlist=(list)request.getattribute(list)for(inti=0;ilist.size();i++)
%/select
Ⅷ java中怎麼向資料庫插入數據
Java程序向資料庫中插入數據,代碼如下:
//首先創建資料庫,(access,oracle,mysql,sqlsever)其中之一,其中access,sqlsever需要配置數據源(odbc);
//然後再eclipse中創建類(ConnDb,Test,TestBean)ConnDb功能為連接資料庫,查詢,插入,刪除,修改數據的類,Test為含有main方法的測試類,TestBean為數據表中的欄位屬性及set,get方法
//以下是ConnDb代碼:
packagedb;
importjava.sql.Connection;
importjava.sql.DriverManager;
import
java.sql.ResultSet;
importjava.sql.SQLException;
import
java.sql.Statement;
importjava.util.ArrayList;
publicclassConnDb{
publicConnectionstartConn(Connectionconn){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:資料庫","用戶名","密碼");
}catch(Exceptione){
System.out.println("連接資料庫時出現錯誤");
}
returnconn;
}
publicArrayListexecuteQuery(Stringsql){
Connectionconn=null;
Statementstmt=null;
ResultSetrs=null;
ArrayListlist=newArrayList();
try{
conn=startConn(conn);
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);//sql為sql語句例如"select*from
表名",從main方法中傳進來,這里用的是ArrayList類將查詢結果存儲起來
while(rs.next()){
TestBeantb=newTestBean();
tb.setTid(rs.getString("tid"));
tb.setTname(rs.getString("tname"));
tb.setTinfo(rs.getString("tinfo"));
list.add(tb);
}
}
catch(SQLExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}finally{
closeConn(rs,stmt,conn);
}
returnlist;
}
publicvoidexecuteUpdate(Stringsql){
Connectionconn=null;
Statementstmt=null;
try{
conn=
startConn(conn);
stmt=conn.createStatement();
stmt.executeUpdate(sql);
}
catch(SQLExceptione){
System.out.println("修改,插入或者刪除資料庫數據時發生錯誤!");
}finally{
closeConn(stmt,conn);
}
}
publicvoidcloseConn(ResultSetrs,Statementstmt,Connectionconn){
try{
if(rs!=
null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
catch(SQLExceptione){
//TODOAuto-generatedcatch
block
System.out.println("關閉資料庫的時候發生錯誤!");
}
}
publicvoidcloseConn(Statementstmt,Connectionconn){
try{
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
catch(SQLExceptione){
//TODOAuto-generatedcatchblock
System.out.println("關閉資料庫的時候發生錯誤!");
}
}
}
Ⅸ java 向資料庫插入數據
java向資料庫中插入數據,可以使用mysql資料庫,使用statement類來操作資料庫,示例如下:
Connectionconn=null;
Statementst=null;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//載入驅動類
conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://<server_name>:<1433>","name","pwd");
conn.setAutoCommit(false);
st=conn.createStatement();
//模擬一個str[i]=nd.getNodeValue().trim()
String[]str=newString[]{"aaa","bbb","ccc","ddd","eee","fff"};
StringsqlStr=null;
for(inti=0;i<str.length;i++){
sqlStr="INSERTINTO<TABLENAME>(<COLNAME>)VALUES('"+str[i]+"')";//向資料庫中插入數據
st.executeUpdate(sqlStr);
}
conn.commit();
}catch(Exceptione){
e.printStackTrace();
}finally{//釋放資料庫的資源
try{
if(st!=null)
st.close();
if(conn!=null&&!conn.isClosed()){
conn.close();
}
}catch(SQLExceptione){
e.printStackTrace();
}
}
Ⅹ 在java中如何將數組里的數據存入資料庫呢
保存位元組數組到資料庫分兩步:
第一、利用FileInputStream.read(byte[])方法把內容讀取到byte[]數組中,比如圖片是由二進制數組成的,就可以定義為一個位元組數組。
第二、在資料庫中對應記錄欄位應該設置為blob類型,這樣就能夠順利保存了
事例代碼如下:
PreparedStatement stmt = connection.generatePreparedStatement("INSERT INTO ... ");
stmt.setBytes(1, yourByteArray);
其中,yourByteArray是你讀出來的字元數組。