I constantly write an error, the database is locked. I just can not understand why this is happening.
db_login.cs
private db_controller _dbctrl = new db_controller();
public SqliteDataReader dataread;
private string query;
//this two inputField,
public void LoginToGo()
{
login = _login.captionText.text;
pass = _pass.text.ToString();
query = "SELECT id from users where users = '" + login + "' AND pass = '" + pass + "'";
try
{
dataread = _dbctrl.ExecuteReader(query);
if(dataread.HasRows & dataread != null)
{
while (dataread.Read())
{
VerifyAdmin();
_dbctrl.Disconnect();
}
}
else
{
errortxt.text = "Неверный логин или пароль, пожалуйста повторите!";
}
}
catch (Exception ex) { errortxt.text = ex.ToString(); }
}
public void VerifyAdmin() //Who are you, admin or user
{
login = _login.captionText.text;
query_access = "SELECT root from users where users = '" + login + "'";
try
{
dataread = _dbctrl.ExecuteReader(query_access);
while (dataread.Read())
{
if(dataread[0].ToString() == "0" || dataread[0].ToString() == null)
{
MainMenu();
}
else
{
AdminMenu();
}
}
}
catch (Exception ex) { errortxt.text = ex.ToString(); }
}
public void AdminMenu()
{
JOIN.SetActive(false);
ADMIN.SetActive(true);
}
public void MainMenu()
{
JOIN.SetActive(false);
MAIN.SetActive(true);
}
db_controller.cs
public SqliteConnection con_db;
public SqliteCommand cmd_db;
public SqliteDataReader rdr_db;
public void connections()
{
try
{
if(Application.platform != RuntimePlatform.Android)
{
path = Application.dataPath + "/StreamingAssets/db.bytes"; // Путь для Windows
}
else
{
path = Application.persistentDataPath + "/db.bytes"; // Путь для Android
if(!File.Exists(path))
{
WWW load = new WWW("jar:file://" + Application.dataPath + "!/assets/" + "db.bytes");
while (!load.isDone) { }
File.WriteAllBytes(path, load.bytes);
}
}
con_db = new SqliteConnection("URI=file:" + path);
con_db.Open();
if (con_db.State == ConnectionState.Open)
{
debugText.text = path.ToString() + " - is connected";
Debug.Log(path.ToString());
}
}
catch (Exception ex)
{
debugText.text = ex.ToString();
}
}
//Тут я создаю метод отключения
public void Disconnect()
{
con_db.Close();
}
public SqliteDataReader ExecuteReader(string query)
{
connections();
try
{
cmd_db = new SqliteCommand(query, con_db);
rdr_db = cmd_db.ExecuteReader();
return rdr_db;
}
catch (Exception ex) { debugText.text = ex.ToString(); return null; }
}
//Тут я записываю данные. Заодно решил проверить закрыто ли соединение.
public void SetDB()
{
if (con_db.State == ConnectionState.Open)
{
Debug.Log("open");
}
else
{
Debug.Log("close!");
}
//The connection is closed. But I can not complete the request cmd_db.ExecuteNonQuery();
connections();
try
{
brand = AutoName.captionText.text;
model = AutoModel.captionText.text;
years = OldAuto.captionText.text;
number = GosNumber.text.ToString();
nusers = UserName.text.ToString();
dbirthday = DBirthday.captionText.text;
mbirthday = MBirthday.captionText.text;
ybirthday = YBirthday.captionText.text;
mobile = Mobile.text.ToString();
cmd_db = new SqliteCommand("INSERT INTO clients(brand,model,years,number,nusers,dbirthday,mbirthday,ybirthday,mobile,groupmodel) values('" + brand + "', '" + model + "','" + years + "','" + number + "','" + nusers + "','" + dbirthday + "','" + mbirthday + "','" + ybirthday + "','" + mobile + "','" +groupmodel+ "')" , con_db);
cmd_db.ExecuteNonQuery(); //Swears, says that the base is locked. And why? I just read the data and the connection was closed.
}
catch (Exception ex) { debugText.text = ex.ToString(); }
Disconnect();
}
the documentation says:
This error code occurs when you try to do two incompatible things with the database at the same time from the same connection to the database.
But the connection with the base is closed.
Maybe I'm missing something, or not doing the right thing. I ask for help to clarify this issue.
Related
How do I accept null values into the SQL Server database with Kotlin? I am trying to make that if the user does not input anything into the column, it will return null instead in the SQL Server. But I failed to do so and a bunch of numbers is saved instead, may I know how can I do it? Below are my codes and the input I got from SQL Server.
For example: 2131231267 and 2131231270 is saved instead of NULL.
fun createGoals()
{
val sqlCon = SQLCon()
checkGoal()
checkTargetAmount()
checkSavedAmount()
checkNote()
if (checkGoal() == true && checkTargetAmount() == true){
Toast.makeText(this, "Creating Goals...", Toast.LENGTH_LONG).show()
connection = sqlCon.connectionClass()!!
if(connection == null)
{
Toast.makeText(this, "Failed to make connection", Toast.LENGTH_LONG).show()
}
else {
try{
val sql :String =
"INSERT INTO Budget(gName,sAmount,Note,tAmount) VALUES ('" + binding.txtGoal.text.toString() + "'" +
",'" + Integer.valueOf(R.id.txtSavedAmount.toString()) + "'" +
",'" + R.id.txtNote.toString()+ "'" +
",'" + Integer.valueOf(binding.txtTargetAmount.text.toString().trim()) + "')"
statement = connection!!.createStatement()
statement!!.executeUpdate(sql)
Toast.makeText(this, "Going In ", Toast.LENGTH_LONG).show()
}
catch (e : Exception){
Log.e("Error", e.message!!)
}
status = true
}
}
}
private fun checkNote() : String?
{
var Note : String? = R.id.txtNote.toString()
if(Note.isNullOrEmpty())
{
Note = " "
}
return Note
}
private fun checkSavedAmount() : String?
{
var savedAmount: String? = R.id.txtSavedAmount.toString()
if(savedAmount.isNullOrEmpty())
{
savedAmount = " "
}
return savedAmount
}
I created a file to read the sensors of my Android Wear. I can tell it is working because my storage is being filled up, but I can't see the folder of the readings. Can you help me out finding out what is wrong with the code?
public class Logging extends Activity implements SensorEventListener {
DecimalFormat df =new DecimalFormat("##.##");
Boolean flag=true;
FileOutputStream outputStream;
TextView displayReading1;
TextView displayReading2;
TextView displayReading3;
TextView displayReading4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final File Project=getDir("Project", Context.MODE_PRIVATE);
if(!Project.exists())
Project.mkdir();
File fileWithinProject=new File (Project+"/","Project.txt");
if(!fileWithinProject.exists())
try {
fileWithinProject.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
// final File file=new File (dirPath,"Project.txt");
/* File file = new File(dirPath, "Project.txt");
try {
if (!file.exists())
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}*/
setContentView(R.layout.activity_logging);
Button start=(Button)findViewById(R.id.StartButton);
Button stop=(Button)findViewById(R.id.StopButton);
//BUTTON START
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=true;
Toast.makeText(getApplicationContext(),"Start Recording Readings",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), ("File in: "+ Project), Toast.LENGTH_LONG).show();
}
}); {
}
//BUTTON STOP
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=false;
Toast.makeText(getApplicationContext(),"Done recording readings",Toast.LENGTH_SHORT).show();
}
});{
}
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor accSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor rotSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
Sensor gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
Sensor gyroSensor = sensorManager.getDefaultSensor((Sensor.TYPE_GYROSCOPE));
sensorManager.registerListener(this, accSensor, 100000000);
sensorManager.registerListener(this, rotSensor, 100000000);
sensorManager.registerListener(this, gravitySensor, 100000000);
sensorManager.registerListener(this, gyroSensor, 100000000);
displayReading1 = (TextView) findViewById(R.id.acc_sensor);
displayReading2 = (TextView) findViewById(R.id.rotational_sensor);
displayReading3 = (TextView) findViewById(R.id.gravity_sensor);
displayReading4 = (TextView) findViewById(R.id.gyro_sensor);
displayReading1.setTextSize(14f);
displayReading2.setTextSize(14f);
displayReading3.setTextSize(14f);
displayReading4.setTextSize(14f);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_logging, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSensorChanged (SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
displayReading1.setText("Accelerometer (m/s2): " +"\nX"+" " +df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X11=event.values[0];
float X12=event.values[1];
float X13=event.values[2];
if( flag) {
try {
// Toast.makeText(getApplicationContext(), ("current location newFile.getAbsolutePath()), Toast.LENGTH_LONG).show();
outputStream = openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(((df.format(X11) + df.format(X12) + df.format(X13)
)).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}
}
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
displayReading2.setText("Rotational Vector: " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X21=event.values[0];
float X22=event.values[1];
float X23=event.values[2];
if( flag) {
try {
outputStream=openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(("Rotational Vector : " +"\nX"+" " +df.format(X21) + "\nY"+" " + df.format(X22) + "\nZ"+" " + df.format(X23)).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}}
if (event.sensor.getType() == Sensor.TYPE_GRAVITY)
displayReading3.setText("Gravity (m/s2): " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE)
displayReading4.setText("Gyroscope (rad/s): " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X31=event.values[0];
float X32=event.values[1];
float X33=event.values[2];
if( flag) {
try {
outputStream = openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(("Gyroscope (rad/s): " + "\nX" + " " + df.format(X31) + "\nY" + " " + df.format(X32) + "\nZ" + " " + df.format(X33)
).getBytes());
//Toast.makeText(getApplicationContext(), "Gyroscope (rad/s): " + "\nX" + " " + df.format(X31) + "\nY" + " " + df.format(X32) + "\nZ" + " " + df.format(X33), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}
}
if (!flag){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
Hi I am trying to customize DBTrigger message in bean Here is code for it, it is displaying my customized message but as well it is displaying DBTrigger message below to my message, Kindly help me to get out of this.
public void saveLataActionListenerNew(ActionEvent actionEvent) {
System.out.println("----on click saved ");
try {
OperationBinding operationBinding = (OperationBinding)getBindings().getOperationBinding("Commit");
Object result = operationBinding.execute();
System.out.println("Errors : " + operationBinding.getErrors());
if (operationBinding.getErrors() != null) {
Iterator it = operationBinding.getErrors().iterator();
System.out.println("error = " + it);
System.out.println("size of Errors - " + operationBinding.getErrors().size());
while (it.hasNext()) {
DMLException error = (DMLException)it.next();
String errorCause = "" + error.getCause();
System.out.println("error.getCause() : " + errorCause);
if (errorCause != null && errorCause.contains("ORA-00001: unique constraint")) {
uniqueConstraint = "Lata is Exists for given State";
showMessage(uniqueConstraint, FacesMessage.SEVERITY_ERROR);
return;
}
}
}
uniqueConstraint = "Record is saved successfully";
showMessage(uniqueConstraint, FacesMessage.SEVERITY_INFO);
System.out.println("---record saved successfully");
// addPlaceCodePfl.setRendered(false);
// addPlaceCodePgl.clearInitialState();
// addPlaceCodePfl.
} catch (Exception e) {
uniqueConstraint = e.getMessage();
showMessage(uniqueConstraint, FacesMessage.SEVERITY_ERROR);
e.printStackTrace();
}
I am trying to change the password of Active directory user and get error code 65. Please see below the source code I used.
public class ADConnection {
DirContext ldapContext;
String baseName = ",CN=Users,DC=wso2,DC=test";
public ADConnection() {
try {
Hashtable ldapEnv = new Hashtable(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, "ldaps://192.168.18.xx:636");
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrator"
+ baseName);
ldapEnv.put(Context.SECURITY_CREDENTIALS, "xxxxxx");
ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
ldapContext = new InitialDirContext(ldapEnv);
} catch (Exception e) {
System.out.println(" bind error: " + e);
e.printStackTrace();
System.exit(-1);
}
}
public void updatePassword(String username, String password) {
try {
String quotedPassword = "\"" + password + "\"";
char unicodePwd[] = quotedPassword.toCharArray();
byte pwdArray[] = new byte[unicodePwd.length * 2];
for (int i = 0; i < unicodePwd.length; i++) {
pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8);
pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff);
}
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("UnicodePwd", pwdArray));
ldapContext.modifyAttributes("cn=" + username + baseName, mods);
//ldapContext.modifyAttributes("cn=" + username, mods);
} catch (Exception e) {
System.out.println("update password error: " + e);
System.exit(-1);
}
}
public static void main(String[] args) {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// the keystore that holds trusted root certificates
System.setProperty("javax.net.ssl.trustStore", "client-truststore.jks");
//System.setProperty("javax.net.debug", "all");
ADConnection adc = new ADConnection();
adc.updatePassword("admin", "pass#word3");
}
}
I used the code from following link.
http://blogs.msdn.com/b/alextch/archive/2012/05/15/how-to-set-active-directory-password-from-java-application.aspx
What is the wrong with this ?
Thanks
I have some links on a page such as:
< a id="Digg" runat="server">< img alt="Digg" id="imgDigg" runat="server" src="~/resources/images/icons/social/digg_32.png" border="0" />< /a>
I have a database table that can "turn" them on or off, in my code behind I have the following:
string[] SocialMedia = new string[] { "Twitter", "Facebook", "LinkedIn", "Digg", "Email", "Print" };
private void CheckForSocialMedia()
{
int i = 0;
for (i = 0; i < SocialMedia.Length; i++)
{
bool AddSocialMedia = (bool)AllowSocialMedia(SocialMedia[i]);
if (AddSocialMedia == false)
{
// Hide the link: Digg.Visible = false;
}
}
}
protected bool AllowSocialMedia(string sSocialMedia)
{
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString);
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = " select Settings.AllowsocialMedia " +
" from ArticleSocialMediaSettings Settings " +
" inner join SocialMedia on Settings.SocialMediaId = SocialMedia.id " +
" where SocialMedia.NetworkName = '" + sSocialMedia + "'" +
" and Settings.RetailerId = '1234'";
myConnection.Open();
try
{
SqlDataReader myReader = myCommand.ExecuteReader();
if (myReader.Read())
{
return (bool)myReader["AllowsocialMedia"];
}
}
catch (Exception ex)
{
throw ex;
}
return true;
}
How can I hide the link if the function returns false? Or is there a better way to do this?
It looks like that is the correct method for checking the database. To hide the link you can use:
document.getElementById("Digg").style.display = "none";
right where your comment is.
Redesigned it using a datalist