Ⅰ 請問sql語法中特殊字元包含哪些,越詳細越好
我曾經寫了一個擴展方法(C#3.0新特性)來處理SQL特殊字元,比較全。提醒一下,不要用js來過濾,js是客戶端運行的,不可靠。代碼如下: #region 處理t-sql中插入的值,過濾特殊字元 /// <summary> /// 處理t-sql中插入的值,防止意外字元導致錯誤 /// </summary> /// <param name="sqlValue">需要插入的值</param> /// <returns></returns> public static string DealWithSqlValue(this string sqlValue) { sqlValue = sqlValue.Trim().Replace("'", "''").Replace("]", "]]").Replace("%", "[%]").Replace("_", "[_]").Replace("^", "[^]"); return sqlValue; } #endregion
採納哦
Ⅱ C#中 <summary>是什麼
是XML注釋
xml注釋都在三個向前的斜線之後(///),兩條斜線表示是一個注釋,編譯器將忽略後面的內容,三條斜線告訴編譯器,後面是XML注釋,需要適當地處理,summary看英文意思就知道應該是對summary下面所寫內容功能的總結、概括
Ⅲ 使用SQL語句創建學生成績資料庫db_Stu,該資料庫有一個主資料庫文件(』F:\ db_Stu.mdf')和事務日誌(』F:
有個問題 剛好符合你的要求:
問題:
當前目錄下的Example.mdb資料庫(這個是Access資料庫)中,內含一個數據表student,有三個欄位:學號、姓名、密碼,並有如干記錄。連接串為string connStr="provider=microsoft.jet.oledb.4.0;datasource="+Server.MapPath("Example.mdb"),資料庫對象不是SQL,而是Access,採用OleDb,即將對象前SQL換成OleDb。
1、編寫一段程序,將student中的數據在DataGridl中顯示出來。
2、編寫一段程序,將學號、姓名、密碼分別為0001,張山,abcd的學生記錄插入到student中。
3、編寫一段程序,判斷資料庫中是否存在學號為「01」、口令為「1234」的學生。
首先連接資料庫(這里的鏈接字元串是在配置文件中)
static string connectionString = ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
private OleDbConnection connection;
public OleDbConnection Connection {
get{
if (connection == null){
connection = new OleDbConnection(connectionString);}
else if (connection.State == System.Data.ConnectionState.Closed) //關閉
{
connection.Open();}
else if (connection.State == System.Data.ConnectionState.Broken) //中斷
{connection.Close();
connection.Open();}
return connection;
}
}
然後是執行查詢語句和插入語句的方法;
/// <summary>
/// 執行SQL語句,返回影響的記錄數
/// </summary>
/// <param name="SQLString">SQL語句</param>
/// <returns>影響的記錄數</returns>
public static int ExecuteSql(string SQLString, params OleDbParameter[] cmdParms)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (System.Data.OleDb.OleDbException E)
{
throw new Exception(E.Message);
}
}
}
}
/// <summary>
/// 執行查詢語句,返回OleDbDataReader
/// </summary>
/// <param name="strSQL">查詢語句</param>
/// <returns>OleDbDataReader</returns>
public static OleDbDataReader ExecuteReader(string strSQL)
{
OleDbConnection connection = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
try
{
connection.Open();
OleDbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (System.Data.OleDb.OleDbException e)
{
throw new Exception(e.Message);
}
}
下面是查詢方法和插入方法
(由於時間問題,你把資料庫欄位都換成你自己的,我這里就不換了)
/// <summary>
/// 增加一條數據
/// </summary>
public int Add()
{
StringBuilder strSql=new StringBuilder();
strSql.Append("insert into [student](");
strSql.Append("[stNum],[Name],[Psd])");
strSql.Append(" values (");
strSql.Append("@stNum,@Name,@Psd)");
OleDbParameter[] parameters = {
new OleDbParameter("@stNum", OleDbType.VarChar,50),
new OleDbParameter("@Name", OleDbType.VarChar),
new OleDbParameter("@Psd", OleDbType.VarChar,50)};
parameters[0].Value = "0001";
parameters[1].Value = "張山";
parameters[2].Value = 「abcd」;
int num=ExecuteCommand(strSql.ToString(),parameters);
return num;
}
/// <summary>
/// 得到所有對象
/// </summary>
/// <returns></returns>
public IList<Student> GetAll()
{
IList<Student> modelList = new List<Student>();
string sqlStr = "select * from [student] ORDER BY [Id] DESC";
using (OleDbDataReader reader = DbHelperOleDb.ExecuteReader(sqlStr))
{
while (reader.Read())
{
Student model = new Student();
if (reader["Id"].ToString() != "")
{
model.Id = int.Parse(reader["Id"].ToString());
}
model.stNum = reader["stNum"].ToString();
model.Name = reader["Name"].ToString();
model.Psd = reader["Psd"].ToString();
modelList.Add(model);
}
}
return modelList;
}
頁面調用添加方法就可以添加一條記錄了
下面市頁面綁定數據
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataBindGV();
}
}
public void DataBindGV()
{
//GetAll()方法我是放在Student類裡面的
gvStudentList.DataSource = new sutdent().GetAll();
gvStudentList.DataBind();
}
頁面DataGrid的代碼如下
<asp:GridView ID="gvStudentList" runat="server" BorderWidth="0px" BackColor="#999999"
CellPadding="1" CellSpacing="1" Width="100%"
AutoGenerateColumns="False">
<EmptyDataTemplate>
沒有資料!
</EmptyDataTemplate>
<HeaderStyle Height="20px" BackColor="#CCCCCC" />
<FooterStyle />
<RowStyle BackColor="#fafafa" Height="20px" />
<EmptyDataRowStyle BackColor="#ffffff" />
<SelectedRowStyle />
<Columns>
<asp:BoundField DataField="Title" HeaderText="學號" SortExpression="stNum">
<ItemStyle Width="170px" />
</asp:BoundField>
<asp:TemplateField HeaderText="名稱" SortExpression="Name">
<ItemTemplate>
<%#Eval("Name")) %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="密碼" SortExpression="Psd">
<ItemTemplate>
<%#Eval("Psd") %>
</ItemTemplate>
<ItemStyle Width="90px" />
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#eeeeee" BorderWidth="0" />
</asp:GridView>
關於第3個,只需把GetAll()方法的查詢語句換一下就行了,換成如下語句:
select * from [student] where [stNum]='01' and [Psd]='1234'
然後再查詢,根據查詢的結果List判斷是否存在,當然你也可以執行
select count(1) from [student] where [stNum]='01' and [Psd]='1234'
判斷返回的數是否大於零就行了,當然這個查詢要另外的查詢語句才行用上面的查詢方法不行了,需要執行ExecuteScalar()了,自己弄吧,很簡單的
如此你的問題全都解決了
Ⅳ 如何在SQL Server中使用正則表達式
在T-SQL中使用正則表達式函數
有想過在T-Sql使用正則表達式嗎?是的,完全可以的,我們可以用SQL SERVER CLR sql function來實現這一功能。
首先,我們在VSTS中創建一Database Project,增一個class, 實現下面的一個方法:
1: /// <summary>
2: /// Regs the ex match.
3: /// </summary>
4: /// <param name="inputValue">The input value.</param>
5: /// <param name="regexPattern">The regex pattern.</param>
6: /// <remarks>Author: Petter Liu http://wintersun.cnblogs.com </remarks>
7: /// <returns>1 match,0 not match</returns>
8: [SqlFunction]
9: public static bool RegExMatch(string inputValue, string regexPattern)
10: {
11: // Any nulls - we can't match, return false
12: if (string.IsNullOrEmpty(inputValue) || string.IsNullOrEmpty(regexPattern))
13: return false;
14:
15: Regex r1 = new Regex(regexPattern.TrimEnd(null));
16: return r1.Match(inputValue.TrimEnd(null)).Success;
17: }
好了,Build後Deploy到你的Target database就OK了,VisualStudio會自動注冊這個程序集的。如果,你想手動注冊程序集,可執行以下的T-SQL:
1: CREATE ASSEMBLY [RegExCLR] FROM 'RegExCLR.dll';
2:
3: -- Add the REGEX function. We want a friendly name
4: -- RegExMatch rather than the full namespace name.
5: -- Note the way we have to specify the Assembly.Namespace.Class.Function
6: -- NOTE the RegExCLR.RegExCLR
7: -- (one is the assembly the other is the namespace)
8: CREATE FUNCTION RegExMatch ( @inputCalue NVARCHAR(4000),
9: @regexPattern NVARCHAR(4000) ) RETURNS BIT
10: AS EXTERNAL NAME RegExCLR.RegExCLR.ClrClass.RegExMatch;
OK, 一切OK的後,我們來測試下:
select COUNT(1) from Threads where dbo.RegExMatch(ThreadId,'^[{|\(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[\)|}]?$')=1
上面的T-SQL是找出Threads表ThreadId是GUID的記錄數。 等於1是匹配,^[{|\(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[\)|}]?$ 匹配GUID的正則表達式。
完了,希望這篇POST對您有幫助。
Ⅳ sql語句中怎麼使用sum函數
sql 中的 sum 配合 case when 就可以添加條件 例 : sum(case when a >0 then a else 0 end ) 將 a列所以大於 0 的值相加。 sum(case when rq >'2015-1-1' and rq
Ⅵ 如何直接執行SQL語句
1、ExecuteQuery方法
看命名,我們很容易聯想到ADO.NET里熟悉的Command的ExecuteNonQuery方法,但是VS的智能提示告訴我們這個方法返回的是一個泛型集合,應該「所思非所得」。下面通過一個簡單方法,驗證我們的猜想(資料庫設計可以參考這一篇):
/// <summary>
/// 直接執行sql語句,獲取總人數
/// </summary>
/// <returns></returns>
publicint GetTotalCount()
{
string strSql = "SELECT COUNT(0) FROM Person(NOLOCK)";
var query = dataContext.ExecuteQuery<int>(strSql);
int result = query.First<int>();
Console.WriteLine();
Console.WriteLine("total count:{0}", result);
return result;
}
調試的時候,通過IntelliTrace跟蹤到:
毫無疑問,上面的圖片說明最初的想法是不正確的,」ADO.NET:執行Reader…」雲雲,讓我們更加堅信它實際執行的應該是ExecuteReader方法。當然最簡單的方法是直接查看它的方法說明:
// 摘要:
// 直接對資料庫執行 SQL 查詢並返回對象。
//
// 參數:
// query:
// 要執行的 SQL 查詢。
//
// parameters:
// 要傳遞給命令的參數數組。注意下面的行為:如果數組中的對象的數目小於命令字元串中已標識的最大數,
則會引發異常。如果數組包含未在命令字元串中引用的對象,則不會引發異常。如果某參數為
// null,則該參數會轉換為 DBNull.Value。
//
// 類型參數:
// TResult:
// 返回的集合中的元素的類型。
//
// 返回結果:
// 由查詢返回的對象的集合。
public IEnumerable<TResult> ExecuteQuery<TResult>(string query, paramsobject[] parameters);
ExecuteQuery方法還有一個非泛型方法:
//
// 摘要:
// 直接對資料庫執行 SQL 查詢。
//
// 參數:
// elementType:
//
要返回的 System.Collections.Generic.IEnumerable<T>
的類型。使查詢結果中的列與對象中的欄位或屬性相匹配的演算法如下所示:如果欄位或屬性映射到特定列名稱,則結果集中應包含該列名稱。如果未映射欄位或屬性,則結果集中應包含其名稱與該欄位或屬性相同的列。通過先查找區分大小寫的匹配來執行比較。如果未找到匹配項,則會繼續搜索不區分大小寫的匹配項。如果同時滿足下列所有條件,則該查詢應當返回(除延遲載入的對象外的)對象的所有跟蹤的欄位和屬性:T
// 是由 System.Data.Linq.DataContext 顯式跟蹤的實體。
System.Data.Linq.DataContext.ObjectTrackingEnabled
// 為 true。實體具有主鍵。否則會引發異常。
//
// query:
// 要執行的 SQL 查詢。
//
// parameters:
// 要傳遞給命令的參數數組。注意下面的行為:如果數組中的對象的數目小於命令字元串中已標識的最大數,
則會引發異常。如果數組包含未在命令字元串中引用的對象,則不會引發異常。如果某參數為
// null,則該參數會轉換為 DBNull.Value。
//
// 返回結果:
// 由查詢返回的對象的 System.Collections.Generic.IEnumerable<T> 集合。
public IEnumerable ExecuteQuery(Type elementType, string query, paramsobject[] parameters);
看它的參數需要多傳遞一個elementType,明顯不如泛型方法簡潔。
2、ExecuteCommand方法
同樣道理,這個方法立刻讓我們聯想到(世界沒有聯想,生活將會怎樣?),聯想到,等等,不知聯想到什麼。然後我們看一下方法使用說明:
//
// 摘要:
// 直接對資料庫執行 SQL 命令。
//
// 參數:
// command:
// 要執行的 SQL 命令。
//
// parameters:
// 要傳遞給命令的參數數組。注意下面的行為:如果數組中的對象的數目小於命令字元串中已標識的最大數,
則會引發異常。如果數組包含未在命令字元串中引用的對象,則不會引發異常。如果任一參數為
// null,則該參數會轉換為 DBNull.Value。
//
// 返回結果:
// 一個 int,表示所執行命令修改的行數。
publicint ExecuteCommand(string command, paramsobject[] parameters);
到這里,看它的返回類型為int,表示執行命令修改的行數,這次很容易想到ExecuteNonQuery方法。對不對呢?通過下面的代碼證明我們的設想:
/// <summary>
/// 直接執行sql語句 根據用戶Id更新體重
/// </summary>
/// <param name="id">用戶Id</param>
/// <param name="destWeight">更新後的體重</param>
/// <returns></returns>
publicint ModifyWeightById(int id, double destWeight)
{
string strSql = string.Format("UPDATE Person SET Weight={0} WHERE Id={1}", destWeight, id);
int result = dataContext.ExecuteCommand(strSql);
Console.WriteLine();
Console.WriteLine("affect num:{0}", result);
return result;
}
調試過程中,通過IntelliTrace可以很清楚地捕獲:「ADO.NET:執行NonQuery…」基本可以斷言我們的設想是正確的。
3、防止sql注入
1和2中,執行sql語句的兩個方法都有一個params 類型的參數,我們又會想到ADO.NET非常重要的sql語句的參數化防止sql注入問題。下面通過一個方法,看看linq2sql可不可以防止sql注入。
(1)、直接執行拼接的sql語句(有風險)
/// <summary>
/// 直接執行sql語句 根據用戶Id更新FirstName
/// </summary>
/// <param name="id">用戶Id</param>
/// <param name="destName">更新後的FirstName</param>
/// <returns></returns>
publicint ModifyNameById(int id, string destName)
{
string strSql = string.Format("UPDATE Person SET FirstName='{0}' WHERE Id={1}", destName, id);
//這么拼接有風險
int result = dataContext.ExecuteCommand(strSql);
Console.WriteLine();
Console.WriteLine("affect num:{0}", result);
return result;
}
然後,在客戶端這樣調用這個方法:
int result = ServiceFactory.CreatePersonService().ModifyNameById(10, "'Anders'");
//更新id為10的人的FirstName
Ⅶ 如何用sql語句 實現分頁查詢
適用於 SQL Server 2000/2005
SELECT TOP 頁大小 *
FROM table1
WHERE id NOT IN
SELECT TOP 頁大小*(頁數-1) id FROM table1 ORDER BY id
Ⅷ 在ms sql中如何使用正則表達式,請給出簡單示例,注釋越詳細越好!感激不盡
MSSQL不支持正則表達式,可以用CLR實現。
1、新建一個MSSQL的資料庫項目,配置到你的資料庫中
2、在資料庫項目中新建一個函數庫,編寫如下代碼:
///<summary>
///驗證是否符合正則表達式
///</summary>
[SqlFunction]
(stringinput,stringregex)
{
returnnewSqlBoolean(Regex.IsMatch(input,regex,RegexOptions.IgnoreCase));
}
然後在資料庫項目上點擊「右鍵」,選擇「部署」
PS:此功能需要MSSQL2005或者以上版本支持
如果你使用的是.NET3.5版本的話,需要在資料庫伺服器上安裝.netframework3.5
目前SQLSERVERCLR不支持.NET4.0,所以如果你使用VS2010開發的話需要把項目版本修改成為.NET2.0/3.5
使用方法:
SELECT*FROM[table]WHEREdbo.RegexIsMatch([ID],'^d+$')=1