本文整理汇总了C#中System.Data.SQLite.SQLiteCommand.ExecuteScalar方法的典型用法代码示例。如果您正苦于以下问题:C# SQLiteCommand.ExecuteScalar方法的具体用法?C# SQLiteCommand.ExecuteScalar怎么用?C# SQLiteCommand.ExecuteScalar使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Data.SQLite.SQLiteCommand
的用法示例。
在下文中一共展示了SQLiteCommand.ExecuteScalar方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ScalarUpdate
/// <summary>
/// Execute a scalar update with the open database
/// connection.
/// </summary>
/// <param name="sql">sql string.</param>
public static void ScalarUpdate(string sql)
{
try
{
SQLiteCommand mycommmand = new SQLiteCommand(sql, manual_cnn);
mycommmand.ExecuteScalar();
mycommmand.CommandText = "SELECT last_insert_rowid()";
Console.WriteLine(mycommmand.ExecuteScalar());
}
catch (Exception ex)
{
throw ex;
}
}
示例2: addButton_Click
void addButton_Click(object sender, RoutedEventArgs e)
{
Button okButton = sender as Button;
WrapPanel wp = okButton.Parent as WrapPanel;
using (SQLiteCommand command = new SQLiteCommand(ConnectionManager.Connection))
{
command.CommandText = "insert into param (param_name,param_type,question) values (@param_name,@param_type,@question); SELECT last_insert_rowid();";
command.Parameters.Add(new SQLiteParameter("@param_name",(wp.Children.FindByName(paramname) as TextBox).Text));
command.Parameters.Add(new SQLiteParameter("@param_type",((wp.Children.FindByName(paramtype) as ComboBox).SelectedItem as ComboBoxItem).Content.ToString()));
command.Parameters.Add(new SQLiteParameter("@question", (wp.Children.FindByName(paramquestion) as TextBox).Text));
//SQLiteParameter p = new SQLiteParameter("@term_group_id");
//p.Value = DBNull.Value;
//command.Parameters.Add(p);
int paramId = int.Parse(command.ExecuteScalar().ToString());
if ((wp.Children.FindByName(termgroup) as ComboBox).IsEnabled)
{
command.CommandText = "insert into term_param (term_group_id,param_id) values (@term_group_id,@param_id)";
command.Parameters.Add(new SQLiteParameter("@term_group_id", ((wp.Children.FindByName(termgroup) as ComboBox).SelectedItem as ComboBoxItem).Tag.ToString()));
command.Parameters.Add(new SQLiteParameter("@param_id", paramId));
command.ExecuteNonQuery();
}
}
UpdateTable();
}
示例3: CheckDBSchema
public static void CheckDBSchema()
{
try
{
using (SQLiteConnection conn = GetConnection())
{
conn.Open();
using (var comm = new SQLiteCommand(conn))
{
comm.CommandText = "SELECT value from DBProperties WHERE name='dbversion'";
var versionNum = (string) comm.ExecuteScalar();
if (versionNum == DBVersion)
{
return;
}
}
conn.Close();
}
}
catch (SQLiteException)
{
}
SpecialTimeLinesRepository.Load();
SpecialTimeLinesRepository.Export();
DeleteDB();
CreateDB();
SpecialTimeLinesRepository.Import();
SpecialTimeLinesRepository.Save();
}
示例4: Authenticate
/// <summary>
/// Authenticate User with giver login data. Returns null if user does not exist
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
public static UserDatabaseError Authenticate(string username, string password, out User user)
{
user = null;
SQLiteConnection connection = new SQLiteConnection(DatabaseManager.CONNECTION_STRING);
SQLiteCommand command = new SQLiteCommand("SELECT salt FROM users WHERE [email protected] and active = 1", connection);
//SQLiteCommand command = new SQLiteCommand("SELECT count(*) FROM users", connection);
command.Parameters.AddWithValue("@username", username);
try
{
connection.Open();
}
catch
{
return UserDatabaseError.ERR_DATABASE_CONNECTION;
}
String salt = (string)command.ExecuteScalar();
if (salt == null || salt == string.Empty)
{
connection.Close();
return UserDatabaseError.ERR_USER_DOES_NOT_EXIST;
}
string hash = DatabaseManager.GetSha256(password + salt);
command.CommandText = "SELECT name, privilege FROM users WHERE [email protected] AND sha256p [email protected]";
command.Parameters.AddWithValue("@password", hash);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
user = new User(username, (string)reader["name"], (User.UserPrivilege)(Int64)reader["privilege"]);
if (user == null)
return UserDatabaseError.ERR_AUTH;
connection.Close();
return UserDatabaseError.ERR_SUCCESS;
}
示例5: Insert
public int Insert()
{
try
{
this.Connection.Open();
//
// TODO: Check for existing ListID
//
SQLiteCommand command = new SQLiteCommand("INSERT INTO List (ListID, ListName) VALUES (@ListID, @ListName); SELECT last_insert_rowid();", this.Connection);
command.Parameters.AddWithValue("@ListID", this.ListID);
command.Parameters.AddWithValue("@ListName", this.ListName);
Object result = command.ExecuteScalar();
this.ID = int.Parse(result.ToString());
}
catch (Exception exception)
{
}
finally
{
this.Connection.Close();
}
return this.ID;
}
示例6: Get
public string Get(string id, string key)
{
try
{
using (var conn = new SQLiteConnection(this._connectionString))
{
const string query = "SELECT value FROM cupcake WHERE id = @id AND key = @key";
using (var cmd = new SQLiteCommand(query, conn))
{
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@key", key);
conn.Open();
object result = cmd.ExecuteScalar();
if (result is DBNull)
return null;
return (string)result;
}
}
}
catch (SQLiteException ex)
{
throw new StorageException(ex.Message, ex);
}
}
示例7: Count
public object Count(String comando)
{
AbreConexao();
SQLiteCommand cmd = new SQLiteCommand(comando, _cnx);
return cmd.ExecuteScalar();
}
示例8: AddBook
private static void AddBook(string bookName, DateTime datePublish, long isbn, string author)
{
db.Open();
using (db)
{
string bookStr = "INSERT INTO books " +
"(titleBook, publishDate, ISBN) VALUES " +
"(@title, @date, @isbn)";
SQLiteCommand addBook = new SQLiteCommand(bookStr, db.ConnectionHandle);
addBook.Parameters.AddWithValue("@title", bookName);
addBook.Parameters.AddWithValue("@date", datePublish);
addBook.Parameters.AddWithValue("@isbn", isbn);
addBook.ExecuteNonQuery();
SQLiteCommand cmdSelectIdentity = new SQLiteCommand("SELECT last_insert_rowid()", db.ConnectionHandle);
long insertedRecordId = (long)cmdSelectIdentity.ExecuteScalar();
string authorStr = "INSERT INTO authors " +
"(Books_idBooks, AuthorName) VALUES " +
"(@bookId, @name)";
SQLiteCommand addAuthor = new SQLiteCommand(authorStr, db.ConnectionHandle);
addAuthor.Parameters.AddWithValue("@bookId", (int)insertedRecordId);
addAuthor.Parameters.AddWithValue("@name", author);
addAuthor.ExecuteNonQuery();
}
}
示例9: AddBook
public static void AddBook(string Title, string authorName, DateTime publish, string ISBN)
{
string connectionStr = "Data Source=..\\..\\book.db;Version=3;";
var connection = new SQLiteConnection(connectionStr);
connection.Open();
using (connection)
{
var addAuthorCommand = new SQLiteCommand("INSERT INTO author(Name) VALUES(@name)", connection);
addAuthorCommand.Parameters.AddWithValue("@name", authorName);
addAuthorCommand.ExecuteNonQuery();
var getAuthIDCommand = new SQLiteCommand("SELECT idAuthor FROM author WHERE Name=" + "@name", connection);
getAuthIDCommand.Parameters.AddWithValue("@name", authorName);
var authID = getAuthIDCommand.ExecuteScalar();
var addBookCommand =
new SQLiteCommand(
"INSERT INTO book(Name,date,ISBN,AuthorID) VALUES(@title,@publish,@ISBN,@authID)",
connection);
addBookCommand.Parameters.AddWithValue("@title", Title);
addBookCommand.Parameters.AddWithValue("@publish", publish);
addBookCommand.Parameters.AddWithValue("@ISBN", ISBN);
addBookCommand.Parameters.AddWithValue("@authID", authID);
addBookCommand.ExecuteNonQuery();
}
}
示例10: LoadProject
public static Project LoadProject(string existingProject)
{
try {
string projectsPath = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location);
Project loadedProj=new Project();
string projectSQL = "SELECT project_base64 FROM project";// WHERE id_project=0"+id_samples.ToString();
SQLiteConnection projectConn = new SQLiteConnection("Data Source="+ projectsPath + @"\\Projects\\" + existingProject + ".db;Version=3;New=False;Compress=True;Synchronous=Off");
SQLiteCommand cmd = new SQLiteCommand(projectSQL,projectConn);
projectConn.Open();
loadedProj = (Project)ConversionUtilities.DeserializeBase64((string)cmd.ExecuteScalar());
// using(SQLiteDataReader sqReader = cmd.ExecuteReader())
// {
// if (sqReader.Read())
// {
// loadedProj = (Project)ConversionUtilities.DeserializeBase64(sqReader.GetString(0));
// }
// }
projectConn.Close();
return loadedProj;
} catch (Exception ex) {
throw ex;
}
}
示例11: MatchStroke
public List<Stroke> MatchStroke(string stroke, AI.Quadrant q, int language)
{
bool b = true;
REDO:
conn = new System.Data.SQLite.SQLiteConnection(@"Data Source=CoreInkLib.dll");
conn.Open();
SQLiteCommand sqc = new SQLiteCommand("SELECT * FROM strokes WHERE directions = '" + stroke + "' AND quadrant='" + Quadrant2Str(q) + "' AND lang = " + language.ToString() + ";", conn);
SQLiteDataReader sqr = sqc.ExecuteReader();
List<Stroke> l = new List<Stroke>();
while (sqr.Read())
{
Stroke st = new Stroke();
st.sid = Convert.ToInt32(sqr[0]);
st.vid = Convert.ToInt32(sqr[1]);
st.cid = Convert.ToInt32(sqr[2]);
st.thisstroke = Convert.ToInt32(sqr[5]);
st.quadrant = sqr[4].ToString();
sqc = new SQLiteCommand("SELECT ifnull(phase,0) FROM strokes WHERE vid = " + st.vid.ToString() + " AND phase >" + st.thisstroke.ToString() + " AND lang=" + language.ToString() + ";", conn);
st.nextstroke = Convert.ToInt32(sqc.ExecuteScalar());
foreach (char c in sqr[3].ToString())
{
st.directions.Add(Convert.ToInt32(c.ToString()));
}
if (b == false)
st.quadrant = "C";
l.Add(st);
}
conn.Close();
if (q.third && l.Count == 0 && b)
{
q.third = false; q.second = true; b = false;
goto REDO;
}
return l;
}
示例12: GetStatus
/// <summary>
/// Given a GUID, returns the current status for that node.
/// </summary>
/// <param name="guid">A unique string that identifies a specific node.</param>
/// <returns>A string with the node status for the given guid</returns>
public string GetStatus(string guid)
{
string status = "";
string statusQuery = "SELECT status FROM Node_Status WHERE guid = @pGUID";
SQLiteCommand statusCmd = new SQLiteCommand(statusQuery, conn);
SQLiteParameter pGUID = new SQLiteParameter("@pGUID", guid);
statusCmd.Parameters.Add(pGUID);
try
{
conn.Open();
status = statusCmd.ExecuteScalar().ToString();
conn.Close();
}
catch (SQLiteException ex)
{
//if anything is wrong with the sql statement or the database,
//a SQLiteException will show information about it.
Debug.Print(ex.Message);
//always make sure the database connection is closed.
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
return status;
}
示例13: button1_Click
// Добавляем новый счет
private void button1_Click(object sender, EventArgs e)
{
String NewSchet = textBox1.Text;
if (String.IsNullOrWhiteSpace(NewSchet)) // Проверяем название счета
{
DialogResult Result = MessageBox.Show("Недопустимое название", "", MessageBoxButtons.OK);
}
else
{
string q = "SELECT COUNT (*) FROM scheta WHERE schet = ('" + NewSchet + "')"; // Проверяем сколько таких же
SQLiteConnection Connection = new SQLiteConnection(string.Format("Data Source={0};", "budget.db"));
SQLiteCommand sqlitecommand = new SQLiteCommand(q, Connection);
Connection.Open();
sqlitecommand.ExecuteNonQuery();
int ans = 0;
ans = Convert.ToInt32(sqlitecommand.ExecuteScalar());
if (ans == 0) // Если таких 0
{
q = "INSERT INTO scheta (schet) VALUES ('" + NewSchet + "')"; // Добавляем
Connection = new SQLiteConnection(string.Format("Data Source={0};", "budget.db"));
sqlitecommand = new SQLiteCommand(q, Connection);
Connection.Open();
sqlitecommand.ExecuteNonQuery();
Connection.Close();
UpdateTable();
}
else // Если есть - сообщаем
{
DialogResult Result = MessageBox.Show("Счет не уникален", "", MessageBoxButtons.OK);
}
}
}
示例14: ExecuteScalar
public object ExecuteScalar(string sql)
{
object value = null;
try
{
var con = CONNECTION.OpenCon();
var cmd = new SQLiteCommand(sql, con);
value = cmd.ExecuteScalar();
cmd.Dispose();
CONNECTION.CloseCon(con);
}
catch(Exception ex)
{
SLLog.WriteError(new LogData
{
Source = ToString(),
FunctionName = "ExecuteScalar Error!",
Ex = ex,
});
return null;
}
return value;
}
示例15: Index
public ViewResult Index(PriceLookup price)
{
var connectionString = @"Data Source=" + Server.MapPath("App_Data/prices.s3db");
var priceDb = new PriceDb(connectionString);
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(price.Upc))
{
priceDb.GetPriceByUpc(price);
if(price.Price == null)
ModelState.AddModelError("NotFound", "UPC not found");
}
else if (!string.IsNullOrEmpty(price.Isbn))
{
var sql = "SELECT Price FROM Prices WHERE Isbn = @isbn";
using (var conn = new SQLiteConnection(connectionString))
{
conn.Open();
var sqlCommand = new SQLiteCommand(sql, conn);
sqlCommand.Parameters.AddWithValue("isbn", price.Isbn);
var result = sqlCommand.ExecuteScalar();
if (result == null)
ModelState.AddModelError("NotFound", "ISBN not found");
else
price.Price = (decimal)result;
conn.Close();
}
}
else
ModelState.AddModelError("Required", "You must enter a UPC or an ISBN");
}
return View(price);
}