How can I attach a password protected sqlite database to a non password protected database?
I have a user sqlite database that is not password protected.
I'm trying to attach a read-only resource database that is password protected.
I could reverse their roles and open the password protected first and attach the user database, but I think it should work this way?
I haven't tried too many things so there is no code to share. but I have googled and can't seem to find any mention of this in the documentation or any examples.
It's all about opening a password protected database directly.
Edit: - heres what i've tried...
using both https://www.sqlite.org/lang_attach.html https://www.sqlite.org/c3ref/open.html
private void btnPasswordAttach_Click(object sender, EventArgs e)
{
string pathToUnProtected = #"C:\Users\BoB\Downloads\DBs\Test Users #1.astc";
string connectionstring = string.Format("Data Source={0};Version=3;BinaryGUID=false", pathToUnProtected);
SQLiteConnection connection = new SQLiteConnection(connectionstring);
connection.Open();
TestQueryMain(connection); **//WORKS**
pathToUnProtected = #"C:\Users\BoB\Downloads\DBs\Test Mods #1.aste";
string commandTextUnProtected = string.Format("ATTACH DATABASE '{0}' AS mods", pathToUnProtected);
SQLiteCommand attachCommandUnProtected = new SQLiteCommand(commandTextUnProtected, connection);
attachCommandUnProtected.ExecuteNonQuery();
TestQueryUnProtected(connection); **//WORKS**
//string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite";
//string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite?password=VanillaIceCream";
//string pathToProtected = #"file:C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite?password=VanillaIceCream";
string pathToProtected = #"C:\Users\BoB\Downloads\DBs\VanillaResources.sqlite;password=VanillaIceCream;";
string password = "VanillaIceCream";
string commandText = string.Format("ATTACH DATABASE '{0}' AS vanilla", pathToProtected);
SQLiteCommand attachCommandProtected = new SQLiteCommand(commandText, connection);
attachCommandProtected.ExecuteNonQuery();
TestQueryProtected(connection); **//NO SUCH TABLE...**
}
private void TestQueryMain(SQLiteConnection connection)
{
string sql = "Select * FROM Notes";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteReader();
}
private void TestQueryProtected(SQLiteConnection connection)
{
try
{
string sql = "SELECT Version from vanilla.DatabaseVersion";
SQLiteCommand command = new SQLiteCommand(sql, connection);
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string i = reader["Version"].ToString();
Debug.Assert(true);
}
}
}
catch (Exception ex)
{
Debug.Assert(true);
}
}
private void TestQueryUnProtected(SQLiteConnection connection)
{
try
{
string sql = "SELECT Version from mods.DatabaseVersion";
SQLiteCommand command = new SQLiteCommand(sql, connection);
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string i = reader["Version"].ToString();
Debug.Assert(true);
}
}
}
catch (Exception ex)
{
Debug.Assert(true);
}
}
found the answer in another post:
https://stackoverflow.com/a/1385690/10099912
to attach a password protected sqlite database you need to use the 'key'word:
"ATTACH DATABASE 'C:\test.sqlite' AS attachedDb KEY 'password'"
Related
using this code:
private async Task<object> ChatNotification()
{
try
{
string cs =dbConnectionStr;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
string cmdText = #"SELECT
[dbo].[ChatMessage].[Id],
[dbo].[ChatMessage].[fkUserId],
[dbo].[ChatMessage].[fkGroupId],
[dbo].[ChatMessage].[Message],
[dbo].[ChatMessage].[DateTime],
[dbo].[ChatMessage].[IPAddress]
FROM [dbo].[ChatMessage] ";
SqlClientPermission permission =
new SqlClientPermission(
PermissionState.Unrestricted);
try
{
permission.Demand();
}
catch (System.Exception ex)
{
}
using (SqlCommand cmd = new SqlCommand(cmdText, con))
{
cmd.Notification = null;
SqlDependency tradeInfoDependency = new SqlDependency(cmd);
tradeInfoDependency.OnChange += DependencyNotify_OnChange;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader reader = cmd.ExecuteReader();
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return Ok( );
}
//dependency******
private async void DependencyNotify_OnChange(object sender, SqlNotificationEventArgs e)
{
ChatNotification().Wait();
var dependency = sender as SqlDependency;
if (dependency == null) return;
if (e.Info == SqlNotificationInfo.Insert || e.Info == SqlNotificationInfo.Merge)
{
var chats = _dbContext.ChatMessage.FromSql(#"SELECT * FROM [dbo].[ChatMessage] " +
"WHERE IsSeenByAdmin=0").OrderBy(c => c.DateTime).ToList();
dependency.OnChange -= DependencyNotify_OnChange;
await _chatAdminHubContext.Clients.All.SendAsync("AdminListen",
chats);
}
}
public Startup(IConfiguration configuration)
{
SqlDependency.Start(dbConnectionStr);
Configuration = configuration;
}
the whole thing works with this connection string which is connected to my localdb:
private readonly string dbConnectionStr=
"Data Source=.;Initial Catalog=signalr;Integrated Security=True;user id=sa;password=******";
but it does not work if i change the connection string to this:
private readonly string dbConnectionStr=
"Data Source=server.*****.com\\MAININSTANCE;Initial Catalog=signalr;Persist Security Info=True;User ID=sa;Password=********";
i can connect to the server and local db with no problem, and can use fetching data with entityframework from both, the connection is made successfully yet the only problem is that when i insert row in localdb [dbo].[ChatMessage], dependency works but when i insert row in servers [dbo].[ChatMessage], it does not.
the only thing i did was to set broker enabled. Could it be related to any permissions on server's db?
UPDATE:
select * from sys.transmission_queue
gives this transmission_status:
An exception occurred while enqueueing a message in the target queue. Error: 15517, State: 1. Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission. 5
I am running this code but it throws an exception and I am not sure why. Any help would be appreciated. I checked the ID and it was the right ID for the record.
protected void DeleteSQLDB(int id)
{
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblStudent WHERE ID=" + id;
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
m_dbConnection.Open();
cmd.ExecuteNonQuery();
m_dbConnection.Close();
}
}
}
catch (Exception ex)
{
Response.Redirect("somwhere");
}
finally
{
}
}
I solved the problem. The reason was that the record was referenced in other tables so I had to remove the references before I could remove the record. Thanks user7396598 for advice about running query manually. This is the code which removes the conversations first and then the student record:
//This deletes the archived student, First any conversations need to be deleted before the record can be removed.
protected void DeleteSQLDB(object id,String studentID)
{
// Response.Redirect(studentID);
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblConversations WHERE StudentID=#studentID";
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
cmd.Parameters.AddWithValue("#studentID", studentID);
m_dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
}
finally
{
DeleteSQLDB2(id);
}
}
protected void DeleteSQLDB2(object id)
{
// Response.Redirect(studentID);
String ConnString = GetConnectAccess();
try
{
using (SqlConnection m_dbConnection = new SqlConnection(ConnString))
{
String sql = "DELETE FROM tblStudent WHERE ID=#ID";
using (SqlCommand cmd = new SqlCommand(sql, m_dbConnection))
{
cmd.Parameters.AddWithValue("#ID", id);
m_dbConnection.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
}
finally
{
Response.Redirect("studentgrid.aspx");
}
}
I don't understand it. This code should work, but there must be something I've done wrong.
Can anyone see what I've done wrong?
string username = tbNewUSER.Text.Trim();
string password = tbNewPass.Text.Trim();
string role = "USER";
string str = "insert into UserValidation (USERNAME, PASSWORD, ROLE) values ('" + username + "','" + password + "','" + role + "')";
MessageBox.Show(username + " Registered", "User registration",MessageBoxButtons.OK, MessageBoxIcon.Information);
clsDB.InsUpDel(str);
And this is the follow up:
public static int InsUpDel(string str)
{
if (!(conn.State == ConnectionState.Open))
conn.Open(); //open connection if closed
int numRows = 0; //counter that checks number of rows affected in the db
try
{
SqlCommand cmd = new SqlCommand(str, conn);
numRows = cmd.ExecuteNonQuery();
cmd = null;
}
catch (SqlException ex)
{
string errorMsg = ex.Message; //more code can be put here
}
if (conn.State == ConnectionState.Open)
conn.Close();
return numRows;
}
Thank you.
Side notes:
Always use parameters for your queries and never string concatenation. For fun see Bobby Tables
Do not use static, there are not many places you need this.
Dont share database connections, create them and destroy them as needed.
Do not store passwords as plain text ever!
Do not catch exceptions you do not plan to handle. Log them and rethrow (using throw;) or do not catch at all. This last one will help you figure out why "its not working"
Updated code
public void UpdateUser() {
var userModel = new UserModel {
Username = tbNewUSER.Text.Trim(),
Password = tbNewPass.Text.Trim(),
Role = "USER"
};
var result = UpdateUser(userModel);
}
public int UpdateUser(UserModel user)
{
const string str = "insert into UserValidation (USERNAME, PASSWORD, ROLE) values (#userName, #password, #role)";
using(var conn = new SqlConnection("your connection string here, hint best to get it from the app.config"))
using(var command = new SqlCommand(str, conn))
{
command.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar, 255) {Value = user.UserName});
command.Parameters.Add(new SqlParameter("#password", SqlDbType.VarChar, 255) {Value = user.Password});
command.Parameters.Add(new SqlParameter("#role", SqlDbType.VarChar, 255) {Value = user.Role});
conn.Open();
return cmd.ExecuteNonQuery();
}
}
UserModel.cs
public class UserModel {
public string UserName {get;set;}
public string Password {get;set;}
public string Role {get;set;}
}
I am trying to import excel file into SQL Server 2005 in C#, but I', getting an error.
Here's my code:
namespace excel
{
public partial class Csharp_Excel : Form
{
public Csharp_Excel()
{
InitializeComponent();
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
private void button1_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
path = Path.Combine(path, "csharp-Excel.xls");
string connStr = #"Server=.\\SQLEXPRESS;Data Source= C:\\Users\\adil pc\\Documents\\Visual Studio 2008\\Projects\\excel\\excel\\bin\\Debug\\csharp-Excel.xls;Initial Catalog=RMS;Integrated Security=SSPI;";
SqlConnection con = new SqlConnection(connStr);
string strCmd = "select * from [sheet1$A1:E7]";
SqlCommand cmd = new SqlCommand(strCmd, con);
try
{
con.Open();
ds.Clear();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
}
}
private void btnsend_Click(object sender, EventArgs e)
{
}
}
The error that I am getting is:
System.Data.SqlClient.SqlException: A network-related or instance-specified error occurred while establishing a connection to SQL Server
I think I got it working I made some changes in connection string :
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\csharp-Excel.xls;Extended Properties=\"Excel 8.0;HDR=Yes;\";
it is working on demo havent implement in actual project once I do will update.
I'm very new to programing and am trying to link a database to a website. I want the website to allow a user to make a username (OrgID) and password (OrgPassword) and have them apear in my database table (Organizer). This is the code I have so far, but I cannot get it to update the information in the database. Does anyone have any suggestions?
protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
if (txtUserName.Text != "" && OrgPassword.Text !="")
{
string cnnString = "Provider= Microsoft.ACE.OLEDB.12.0; Data Source =C:/Users/codym/Desktop/Fall 2011/Information Systems/Project/CampuSpaceDatabase2.accdb";
OleDbConnection cnx = new OleDbConnection(cnnString);
OleDbDataAdapter adapter = new OleDbDataAdapter();
string cmdText= "SELECT * FROM Organizer";
OleDbCommand cmd = new OleDbCommand(cmdText, cnx);
adapter.SelectCommand= cmd;
adapter.Fill(Organizer);
Session["Organizer"]= Organizer;
Organizer= ((DataTable)Session["Organizer"]);
string orgname = OrgID.Text;
string orgpass = OrgPassword.Text;
foreach (DataRow in Organizer.Rows)
{
if(row["OrgID"].ToString() == orgname & row["OrgPassword"].ToString() == orgpass)
{
errLabel.Text = "Welcome "+ row["OrgID"].ToString();
return;
}
else
{
errLabel.Text = "OrgID/Password Invalid";
return;
}
}
}
}
It looks like you are missing opening the connection:
OleDbConnection cnx = new OleDbConnection(cnnString);
cnx.Open();