JDBC鏈接SQL Server2008,解決中文亂碼和轉義問題

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class InitReportData {
	/**
	 * @param args
	 */
	public static void main(String[] args) throws SQLException{
		// TODO Auto-generated method stub

			Connection conn = null;
			Statement stmt = null;
			String JDriver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
			String connectDB="jdbc:sqlserver://localhost:1433;DatabaseName=osi_prod";
			String user="sa";
			String pwd="123456";
			try {
				// 動態導入數據庫的驅動 
				Class.forName(JDriver);
				// 獲取數據庫連接 
				conn = DriverManager.getConnection(connectDB,user,pwd);
				
				String[] series={"中文"};
				String[] category={"中文1","中文2",""};
				String[][] value={
						{"中文3","99.99%",""}
		 				  };
				String tableName="osi_report_DailyProduction";
				String type="crosstabDataRight5";
				int seriesLen=series.length;
				int categoryLen=category.length;
				String sql="";
				for(int i=0;i<seriesLen;i++){
					 for(int j=0;j<categoryLen;j++){
				         	if(value[i][j]!=null){
				         	    // 創造SQL語句 
								sql = "INSERT INTO "+tableName+" (type,series,category,value) VALUES (N'"+type+"',N'"+series[i]+"',N'"+category[j]+"', N'"+value[i][j]+"')";
								// 執行SQL語句 
								stmt = conn.createStatement();
								stmt.executeUpdate(sql);
								System.out.println("插入數據成功");
				         	}    	          
					 }
				}
				
			} catch (Exception e) {	
				e.printStackTrace();
				stmt.close();
				conn.close();
			}
		}

}

在字段值前加個N就能夠解決亂碼了,就這麼簡單 java

sql server有兩個轉義符: 
' 默認狀況下, '是字符串的邊界符, 若是在字符串中包含', 則必須使用兩個', 第1個'就是轉義符 
另外一個轉義符是" 
當SET QUOTED_IDENTIFIER OFF時, "是字符串邊界符, 字符串中的"必須用兩個"表示 sql

相關文章
相關標籤/搜索