當前位置:首頁 » 編程語言 » web連接sql資料庫代碼
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

web連接sql資料庫代碼

發布時間: 2022-07-17 13:14:45

⑴ 如何用web 訪問sql資料庫

public Connection getNewConnection(){
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();

⑵ java web 與sql 2008相連接做個項目但知道java web連接資料庫的語句該如何寫

java 文件
//取得資料庫連接資源文件
private static Properties getProp() throws Exception {
Properties p = new Properties();
FileInputStream is = null;
try {
is = new FileInputStream(".\\conf\\connect.prop");
p.load(is);
} finally {
if (is != null)
is.close();
}
return p;
}

//取得源資料庫連接
private static Connection getConnection1(Properties p) throws Exception {
String sURL = (String) p.get("db1.URL");
String sUser = (String) p.get("db1.user");
String sPasswd = (String) p.get("db1.password");

Class.forName("net.sourceforge.jtds.jdbc.Driver"); return DriverManager.getConnection(sURL, sUser, sPasswd);
}

conf.properties:

#源資料庫連接
db1.URL=jdbc:jtds:sqlserver://127.0.0.1:1433/stu
db1.user=sa
db1.password=123

⑶ ASP.NET中WEB.config連接網路伺服器SQL 2005資料庫,代碼怎麼寫

ASP.NET程序中的web.config中的連接字元串為:<add name="Conn" connectionString="server=.;uid=sa;pwd=seeyon;database=Dsystem;" />,name是指的在程序寫好的鏈接資料庫的方法名,connectionString中就是我們與資料庫連接配置參數:server表示資料庫伺服器的名字和IP地址,uid是指資料庫的用戶名,pwd是資料庫登錄密碼,database是指資料庫的名字。

ASP.NET程序與sql server 2005資料庫連接不單是需要在配置文件中配置好資料庫名、用戶名、密碼、IP地址。還需要在程序中也要寫好與資料庫的連接方法,然後在web.config中來調用才能正常連接,這樣程序在使用過程中才不會報與資料庫連接錯誤。

1、ASP.NET程序與sql server 2005資料庫連接方法代碼:(註:與資料庫連接的方法有很多,但是都是大同小異)

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Data.SqlClient;
usingSystem.Data.OleDb;
usingSystem.Data.Sql;
namespaceDLL
{
publicclassDBHelper
{
publicstaticstringconn=ConfigurationManager.ConnectionStrings["Conn"].ToString();
//publicstaticstringconn=ConfigurationManager.AppSettings["SqlConnString"].ToString();
staticSqlConnectioncon=null;
///<summary>
///判斷資料庫連接狀態
///</summary>
///<returns></returns>
()
{
try
{
if(con==null)
{
con=newSqlConnection(conn);
}
if(con.State==ConnectionState.Broken)
{
con.Close();
con.Open();
}
if(con.State==ConnectionState.Closed)
{
con.Open();
}

}
catch(Exceptionex)
{

throwex;
}
returncon;
}
(stringsql,SqlParameter[]par)
{
SqlCommandcom=newSqlCommand(sql,getConnection());
if(par!=null)
{
foreach(SqlParameterparameterinpar)
{
if(parameter.Value==null)
{
parameter.Value=DBNull.Value;
}
com.Parameters.Add(parameter);

}

}
returncom;
}
publicstaticDataSetDataset(stringsql,SqlParameter[]par,stringtableName)
{
DataSetset=newDataSet();
SqlCommandcomm=NewMethod(sql,par);
if(tableName==null||tableName=="")
{
tableName="tableName";
}
SqlDataAdapterdapter=newSqlDataAdapter(sql,getConnection());
dapter.Fill(set,tableName);
returnset;
}
publicstaticDataTableTable(stringsql,SqlParameter[]par,stringtableName)
{
DataTabletable=newDataTable();
try
{
table=Dataset(sql,par,tableName).Tables[0];
returntable;
}
catch(Exceptionex)
{

throwex;
}

}
(stringsql,SqlParameter[]par)
{
SqlDataReaderred=null;
SqlCommandcomm=NewMethod(sql,par);
try
{
red=comm.ExecuteReader();
}
catch(Exceptionex)
{
red.Close();
con.Close();
throwex;
}
returnred;
}
publicstaticintExecut(stringsql,SqlParameter[]par)
{
intnum=0;
SqlCommandcom=NewMethod(sql,par);
try
{
num=com.ExecuteNonQuery();
}
catch(Exceptionex)
{
num=0;
}
con.Close();
returnnum;
}

}

}

2、web.config配置文件的連接代碼為:

<?xmlversion="1.0"encoding="UTF-8"?>
<!--
注意:除了手動編輯此文件外,您還可以使用
Web管理工具來配置應用程序的設置。可以使用VisualStudio中的
「網站」->「Asp.Net配置」選項。
設置和注釋的完整列表可以在
machine.config.comments中找到,該文件通常位於
WindowsMicrosoft.NetFrameworkvx.xConfig中
-->
<configuration>
<appSettings>
</appSettings>
<!--資料庫連接字元串-->
<connectionStrings>
<addname="Conn"connectionString="server=.;uid=sa;pwd=seeyon;database=Dsystem;"/>
</connectionStrings>
<system.web>
<!--
設置compilationdebug="true"可將調試符號
插入已編譯的頁面中。
但由於這會影響性能,因此請僅在開發過程中將此值
設置為true。
-->
<compilationdebug="true">
</compilation>
<!--
通過<authentication>節可以配置
安全身份驗證模式,ASP.NET
使用該模式來識別來訪用戶身份。
-->
<authenticationmode="Windows"/>
<!--
如果在執行請求的過程中出現未處理的錯誤,
則通過<customErrors>節
可以配置相應的處理步驟。具體而言,
開發人員通過該節可配置要顯示的html錯誤頁,
以代替錯誤堆棧跟蹤。
<customErrorsmode="RemoteOnly"defaultRedirect="GenericErrorPage.htm">
<errorstatusCode="403"redirect="NoAccess.htm"/>
<errorstatusCode="404"redirect="FileNotFound.htm"/>
</customErrors>
-->
</system.web>
<system.webServer>
<defaultDocument>
<files>
<addvalue="Login.aspx"/>
</files>
</defaultDocument>
</system.webServer>
</configuration>

⑷ 在vs2008 Web.config 連接 SqlServer2005,代碼如何寫

一般使用這個資料庫連接字元可以通用"server=.;database=run2005;uid=sa;pwd=;"其中server是伺服器名database是資料庫名uid是登錄資料庫的名字pwd是登錄密碼

⑸ C# web Web.config里sql連接資料庫

訪問資料庫有兩種方式:
Windows身份驗證登錄(不需要用戶名和密碼,適用於訪問本地資料庫,應用程序和SQL軟體安裝在同一台伺服器)
SQL Server 身份驗證登錄(適用於訪問其他計算機的資料庫,當然也可以用這種方式訪問本地資料庫)
根據樓主的情況應該用 SQL Server 身份驗證登錄
資料庫連接字元串一般寫在 connectionStrings節點下,非強制性(如寫在appsettings節點下),只不過這樣可以用
ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
方便訪問
以下是筆者的一個 web.config 文件的內容
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="connString" connectionString="Data Source=.;Initial Catalog=TestDatabase;Integrated Security=SSPI"/>
</connectionStrings>
</configuration>

附:資料庫連接字元串的寫法

SQL Server connection strings
SQL ODBC connection strings
Standard Security:< br> "Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name;Uid=Your_Username;Pwd=Your_Password;"

Trusted connection:< br> "Driver={SQLServer};Server=Your_Server_Name;Database=Your_Database_Name;Trusted_Connection=yes;"
SQL OLE DB connection strings
Standard Security:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;"

Trusted connection:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;"
SQL OleDbConnection .NET strings
Standard Security:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;"

Trusted connection:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;"
SQL SqlConnection .NET strings
Standard Security:
1. "Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;" < br>2. "Server=Your_Server_Name;Database=Your_Database_Name;UserID=Your_Username;Password=Your_Password;Trusted_Connection=False"

Trusted connection:
1. "Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;"
2."Server=Your_Server_Name;Database=Your_Database_Name;Trusted_Connection=True;"

希望回答對你有幫助

⑹ java web 怎麼連接sql資料庫

JAVA Web開發中與資料庫的連接操作,配置:
1、新建資料庫。
新建登錄角色,在新建資料庫的時候把資料庫的所有權交給你新建的角色。用用戶和密碼控制資料庫。保證資料庫的安全。

2、編寫context.xml文件 Xml文件的目的是封裝用戶和密碼,也是封裝的一種,方便操作。
以下為context.xml文件樣例:
<?xml version="1.0" encoding="utf-8"?>
<Context reloadable = "true">
<Resource
name="jdbc/sampleHS"
type="javax.sql.DataSource"
maxActive="14"
maxIdle="10"
username="hstaoshu"
maxWait="5000"
driverClassName="org.postgresql.Driver"
password="hstaoshu"
url="jdbc:postgresql://localhost:5432/hstaoshu"/>
</Context>
詳細說明:
name="jdbc/sampleHS"裡面的ssampHS是可改名稱,建議根據需要自己命名;
username="hstaoshu"
password="hstaoshu"此兩項為你新建的資料庫登錄角色用戶名和密碼信息,只有匹配 了才能訪問。這里簡單為了表示,把用戶名和密碼弄成了跟資料庫名字一樣。其實這是很不安全的。
url="jdbc:postgresql://localhost:5432/hstaoshu"/>
這是連接資料庫的URl,就像訪問網站的地址一樣。沒有這個是無法訪問資料庫的。localhost:5432表示本地埠。一般不需要改動,如果你在配置資料庫的時候改動過埠,那麼你需要把它改回來。/hstaoshu是你的資料庫名稱。
其他選項請勿擅自改動。

3、編寫DAO類。
DAO類的作用是與數據連接後,對資料庫的一些操作的封裝。封裝的作用。為了更好的數據管理。
DAO是真正如何使用資料庫的關鍵步驟,前兩步只是部署和配置。
private static InitialContext context = null;
private DataSource dataSource = null;
//一般把跟資料庫的連接放在DAO類的構造函數里,只要被實例化,就能和資料庫連接。
public BookDAO() {
try {
if (context == null) {
context = new InitialContext();
}
dataSource = (DataSource) context.lookup("java:comp/env/jdbc/sampleHS");
// 連接資料庫,前面在context.xml文件配置里的URl
} catch (NamingException e2) {
e2.printStackTrace();
}
}
public Connection getConnection() {
Connection conn = null;
try {
conn = dataSource.getConnection();// 獲得數據源的連接對象
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

做完上面的三步操作,開發環境已經完全和資料庫連接OK,可以開始資料庫的操作了。一般來說,對資料庫的操作語句都是提前封裝好的。這樣修改起來會對下面的代碼影響降到最小。
如下:
// ------------------資料庫操作語句代碼封裝------------------

/* 查看所有圖書 */
private static final String SELECT_ALL_SQL = "SELECT * FROM book";
那麼在使用的時候只要直接調用:
pstmt = conn.prepareStatement(SELECT_ALL_SQL);

⑺ 用web service方法使android連接到SQL sever的具體代碼

1.可以改用SQL Server身份驗證方式。在安全性-登錄名中添加一個SQL Server身份驗證方式登錄的用戶。


C#的代碼裡面資料庫連接字元串還是粘貼屬性裡面的連接字元串,把密碼改成自己的密碼。
private String ConServerStr = "Data Source=2013-20160523DL;Initial Catalog=test;User ID=houjingyi;Password=*******";
2.一定要先在webservice裡面確認對資料庫的操作沒有問題,再去調android程序。只看到頁面出來了很可能資料庫連接有問題,這樣即使android程序沒問題也調不出來。
3.android4.0以後不允許在主線程中訪問網路,因為萬一主線程阻塞了,會使得界面沒有響應。我們開啟線程訪問即可。

[java]view plain

  • publicList<HashMap<String,String>>getAllInfo(finalHandlermyhandler)

  • {

  • HashMap<String,String>tempHash=newHashMap<String,String>();

  • List<HashMap<String,String>>list=newArrayList<HashMap<String,String>>();

  • tempHash.put("Cno","Cno");

  • tempHash.put("Cname","Cname");

  • tempHash.put("Cnum","Cnum");

  • list.clear();

  • arrayList1.clear();

  • arrayList2.clear();

  • arrayList3.clear();

  • list.add(tempHash);

  • newThread()

  • {

  • publicvoidrun()

  • {

  • arrayList1=Soap.GetWebServer("selectAllCargoInfor",arrayList1,arrayList2);

  • Messagemsg=newMessage();

  • msg.what=0x123;

  • msg.obj=arrayList1;

  • myhandler.sendMessage(msg);

  • }

  • }.start();

  • returnlist;

  • }

  • publicvoidinsertCargoInfo(StringCname,StringCnum)

  • {

  • arrayList1.clear();

  • arrayList2.clear();

  • arrayList1.add("Cname");

  • arrayList1.add("Cnum");

  • arrayList2.add(Cname);

  • arrayList2.add(Cnum);

  • newThread()

  • {

  • publicvoidrun()

  • {

  • try

  • {

  • Soap.GetWebServer("insertCargoInfo",arrayList1,arrayList2);

  • }

  • catch(Exceptione)

  • {

  • }

  • }

  • }.start();

  • }

  • publicvoiddeleteCargoInfo(StringCno)

  • {

  • arrayList1.clear();

  • arrayList2.clear();

  • arrayList1.add("Cno");

  • arrayList2.add(Cno);

  • newThread()

  • {

  • publicvoidrun()

  • {

  • try

  • {

  • Soap.GetWebServer("deleteCargoInfo",arrayList1,arrayList2);

  • }

  • catch(Exceptione)

  • {

  • }

  • }

  • }.start();

  • }

  • 4.android4.0以後子線程里是不能對主線程的UI進行改變的,因此就引出了Handler。主線程里定義Handler供子線程里使用。
  • [java]view plain

  • finalHandlermyhandler=newHandler()

  • {

  • publicvoidhandleMessage(Messagemsg)

  • {

  • if(msg.what==0x123)

  • {

  • ArrayList<String>drrayList=(ArrayList<String>)msg.obj;

  • for(intj=0;!drrayList.isEmpty()&&j+2<drrayList.size();j+=3)

  • {

  • HashMap<String,String>hashMap=newHashMap<String,String>();

  • hashMap.put("Cno",drrayList.get(j));

  • hashMap.put("Cname",drrayList.get(j+1));

  • hashMap.put("Cnum",drrayList.get(j+2));

  • list.add(hashMap);

  • }

  • adapter=newSimpleAdapter(

  • MainActivity.this,list,

  • R.layout.adapter_item,

  • newString[]{"Cno","Cname","Cnum"},

  • newint[]{R.id.txt_Cno,R.id.txt_Cname,R.id.txt_Cnum});

  • listView.setAdapter(adapter);

  • }

  • }

  • };

⑻ 求在C#2005 WEB中讀取SQL資料庫內容的一些代碼

一個例子:
//先導入命名空間
using System.Data;
using System.SqlClient;
//代碼大體如此:
SqlConnection Conn = new SqlConnection("連接字元串");
SqlCommand Cmd = new SqlCommand("SQL查詢語句",Conn);
Cmd.Connection.Open(); //打開資料庫連接
SqlDataReader Reader = Cmd.ExecuteReader();返回 SqlDataReader 對象
while(Reader.Read()) //讀取一條記錄
{
//Reader["欄位名"]就可以獲取資料庫中對應欄位的值,比如: str1=Reader["Name"].ToString();
}
Reader.Close();//關閉讀取
Cmd.Connection.Close();//關閉連接

⑼ ASP.NET中如何用WEB.CONFIG文件來連接SQL資料庫

<connectionStrings>
<add name="xiangCtr" connectionString="Data Source=.(本機用點就行了,如果上傳到空間就要寫資料庫IP如「124.24.122.147」);Initial Catalog=資料庫名;User ID=登陸帳戶;password=密碼" providerName="System.Data.SqlClient"/></connectionStrings> ACCESS的資料庫跟SQL的規則肯定有所不同的啊、 你只要記得每個資料庫在配置文件裡面的寫法就行了。 其實這個很簡單的。 頁面調用為 SqlConnection con=System.Configuration.ConfigurationManager.ConnectionStrings["xiangCtr"].ConnectionString //這里["xiangCtr"].寫你在配置文件裡面定義要鏈接資料庫的name。 然後直接用這個實例化的con就行了。

⑽ 在ASP.NET的web.config中配置好SQL的資料庫連接,在代碼中如何調用

name是連接字元串的名字
connectionString 是他的值。。
Data Source表示數據源,也就是sql服務的路徑和名稱,一般為IP地址
user id 是帳號, p.....。。
Initial Catalog表示資料庫名稱
Integrated Security=True表示打開數庫鏈接時集成windows身份驗證
---------
另外:
有三種方式可以修改連接字元串。我知道的。
一個是點「修改連接」再點高級 最下面的datasource就是你要的連接字元串。。。
一個是用sqldatasource會自動的寫到web.config 另存為 連接字元串可以添加新的連接字元串
還有一個,一點要點完成,如果不需要哪個sqldatasource不用的話可以刪掉,字元串留下來。
還有就是手工,用多了就知道了。
---------